SemaType.cpp revision 235864
1193326Sed//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements type-related semantic analysis.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14234353Sdim#include "clang/Sema/ScopeInfo.h"
15212904Sdim#include "clang/Sema/SemaInternal.h"
16212904Sdim#include "clang/Sema/Template.h"
17221345Sdim#include "clang/Basic/OpenCL.h"
18193326Sed#include "clang/AST/ASTContext.h"
19223017Sdim#include "clang/AST/ASTMutationListener.h"
20198092Srdivacky#include "clang/AST/CXXInheritance.h"
21193326Sed#include "clang/AST/DeclObjC.h"
22193326Sed#include "clang/AST/DeclTemplate.h"
23198092Srdivacky#include "clang/AST/TypeLoc.h"
24198398Srdivacky#include "clang/AST/TypeLocVisitor.h"
25193326Sed#include "clang/AST/Expr.h"
26198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
27212904Sdim#include "clang/Basic/TargetInfo.h"
28221345Sdim#include "clang/Lex/Preprocessor.h"
29234353Sdim#include "clang/Parse/ParseDiagnostic.h"
30212904Sdim#include "clang/Sema/DeclSpec.h"
31224145Sdim#include "clang/Sema/DelayedDiagnostic.h"
32234353Sdim#include "clang/Sema/Lookup.h"
33195341Sed#include "llvm/ADT/SmallPtrSet.h"
34198954Srdivacky#include "llvm/Support/ErrorHandling.h"
35193326Sedusing namespace clang;
36193326Sed
37198893Srdivacky/// isOmittedBlockReturnType - Return true if this declarator is missing a
38198893Srdivacky/// return type because this is a omitted return type on a block literal.
39198893Srdivackystatic bool isOmittedBlockReturnType(const Declarator &D) {
40198893Srdivacky  if (D.getContext() != Declarator::BlockLiteralContext ||
41198893Srdivacky      D.getDeclSpec().hasTypeSpecifier())
42198893Srdivacky    return false;
43198893Srdivacky
44198893Srdivacky  if (D.getNumTypeObjects() == 0)
45198893Srdivacky    return true;   // ^{ ... }
46198893Srdivacky
47198893Srdivacky  if (D.getNumTypeObjects() == 1 &&
48198893Srdivacky      D.getTypeObject(0).Kind == DeclaratorChunk::Function)
49198893Srdivacky    return true;   // ^(int X, float Y) { ... }
50198893Srdivacky
51198893Srdivacky  return false;
52198893Srdivacky}
53198893Srdivacky
54221345Sdim/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
55221345Sdim/// doesn't apply to the given type.
56221345Sdimstatic void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
57221345Sdim                                     QualType type) {
58226633Sdim  bool useExpansionLoc = false;
59221345Sdim
60221345Sdim  unsigned diagID = 0;
61221345Sdim  switch (attr.getKind()) {
62221345Sdim  case AttributeList::AT_objc_gc:
63221345Sdim    diagID = diag::warn_pointer_attribute_wrong_type;
64226633Sdim    useExpansionLoc = true;
65221345Sdim    break;
66221345Sdim
67224145Sdim  case AttributeList::AT_objc_ownership:
68224145Sdim    diagID = diag::warn_objc_object_attribute_wrong_type;
69226633Sdim    useExpansionLoc = true;
70224145Sdim    break;
71224145Sdim
72221345Sdim  default:
73221345Sdim    // Assume everything else was a function attribute.
74221345Sdim    diagID = diag::warn_function_attribute_wrong_type;
75221345Sdim    break;
76221345Sdim  }
77221345Sdim
78221345Sdim  SourceLocation loc = attr.getLoc();
79226633Sdim  StringRef name = attr.getName()->getName();
80221345Sdim
81221345Sdim  // The GC attributes are usually written with macros;  special-case them.
82226633Sdim  if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
83221345Sdim    if (attr.getParameterName()->isStr("strong")) {
84221345Sdim      if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
85221345Sdim    } else if (attr.getParameterName()->isStr("weak")) {
86221345Sdim      if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
87221345Sdim    }
88221345Sdim  }
89221345Sdim
90221345Sdim  S.Diag(loc, diagID) << name << type;
91221345Sdim}
92221345Sdim
93218893Sdim// objc_gc applies to Objective-C pointers or, otherwise, to the
94218893Sdim// smallest available pointer type (i.e. 'void*' in 'void**').
95218893Sdim#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
96224145Sdim    case AttributeList::AT_objc_gc: \
97224145Sdim    case AttributeList::AT_objc_ownership
98203955Srdivacky
99218893Sdim// Function type attributes.
100218893Sdim#define FUNCTION_TYPE_ATTRS_CASELIST \
101218893Sdim    case AttributeList::AT_noreturn: \
102218893Sdim    case AttributeList::AT_cdecl: \
103218893Sdim    case AttributeList::AT_fastcall: \
104218893Sdim    case AttributeList::AT_stdcall: \
105218893Sdim    case AttributeList::AT_thiscall: \
106218893Sdim    case AttributeList::AT_pascal: \
107221345Sdim    case AttributeList::AT_regparm: \
108221345Sdim    case AttributeList::AT_pcs \
109203955Srdivacky
110218893Sdimnamespace {
111218893Sdim  /// An object which stores processing state for the entire
112218893Sdim  /// GetTypeForDeclarator process.
113218893Sdim  class TypeProcessingState {
114218893Sdim    Sema &sema;
115218893Sdim
116218893Sdim    /// The declarator being processed.
117218893Sdim    Declarator &declarator;
118218893Sdim
119218893Sdim    /// The index of the declarator chunk we're currently processing.
120218893Sdim    /// May be the total number of valid chunks, indicating the
121218893Sdim    /// DeclSpec.
122218893Sdim    unsigned chunkIndex;
123218893Sdim
124218893Sdim    /// Whether there are non-trivial modifications to the decl spec.
125218893Sdim    bool trivial;
126218893Sdim
127221345Sdim    /// Whether we saved the attributes in the decl spec.
128221345Sdim    bool hasSavedAttrs;
129221345Sdim
130218893Sdim    /// The original set of attributes on the DeclSpec.
131226633Sdim    SmallVector<AttributeList*, 2> savedAttrs;
132218893Sdim
133218893Sdim    /// A list of attributes to diagnose the uselessness of when the
134218893Sdim    /// processing is complete.
135226633Sdim    SmallVector<AttributeList*, 2> ignoredTypeAttrs;
136218893Sdim
137218893Sdim  public:
138218893Sdim    TypeProcessingState(Sema &sema, Declarator &declarator)
139218893Sdim      : sema(sema), declarator(declarator),
140218893Sdim        chunkIndex(declarator.getNumTypeObjects()),
141221345Sdim        trivial(true), hasSavedAttrs(false) {}
142218893Sdim
143218893Sdim    Sema &getSema() const {
144218893Sdim      return sema;
145207619Srdivacky    }
146218893Sdim
147218893Sdim    Declarator &getDeclarator() const {
148218893Sdim      return declarator;
149218893Sdim    }
150218893Sdim
151218893Sdim    unsigned getCurrentChunkIndex() const {
152218893Sdim      return chunkIndex;
153218893Sdim    }
154218893Sdim
155218893Sdim    void setCurrentChunkIndex(unsigned idx) {
156218893Sdim      assert(idx <= declarator.getNumTypeObjects());
157218893Sdim      chunkIndex = idx;
158218893Sdim    }
159218893Sdim
160218893Sdim    AttributeList *&getCurrentAttrListRef() const {
161218893Sdim      assert(chunkIndex <= declarator.getNumTypeObjects());
162218893Sdim      if (chunkIndex == declarator.getNumTypeObjects())
163218893Sdim        return getMutableDeclSpec().getAttributes().getListRef();
164218893Sdim      return declarator.getTypeObject(chunkIndex).getAttrListRef();
165218893Sdim    }
166218893Sdim
167218893Sdim    /// Save the current set of attributes on the DeclSpec.
168218893Sdim    void saveDeclSpecAttrs() {
169218893Sdim      // Don't try to save them multiple times.
170221345Sdim      if (hasSavedAttrs) return;
171218893Sdim
172218893Sdim      DeclSpec &spec = getMutableDeclSpec();
173218893Sdim      for (AttributeList *attr = spec.getAttributes().getList(); attr;
174218893Sdim             attr = attr->getNext())
175218893Sdim        savedAttrs.push_back(attr);
176218893Sdim      trivial &= savedAttrs.empty();
177221345Sdim      hasSavedAttrs = true;
178218893Sdim    }
179218893Sdim
180218893Sdim    /// Record that we had nowhere to put the given type attribute.
181218893Sdim    /// We will diagnose such attributes later.
182218893Sdim    void addIgnoredTypeAttr(AttributeList &attr) {
183218893Sdim      ignoredTypeAttrs.push_back(&attr);
184218893Sdim    }
185218893Sdim
186218893Sdim    /// Diagnose all the ignored type attributes, given that the
187218893Sdim    /// declarator worked out to the given type.
188218893Sdim    void diagnoseIgnoredTypeAttrs(QualType type) const {
189226633Sdim      for (SmallVectorImpl<AttributeList*>::const_iterator
190218893Sdim             i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
191221345Sdim           i != e; ++i)
192221345Sdim        diagnoseBadTypeAttribute(getSema(), **i, type);
193218893Sdim    }
194218893Sdim
195218893Sdim    ~TypeProcessingState() {
196218893Sdim      if (trivial) return;
197218893Sdim
198218893Sdim      restoreDeclSpecAttrs();
199218893Sdim    }
200218893Sdim
201218893Sdim  private:
202218893Sdim    DeclSpec &getMutableDeclSpec() const {
203218893Sdim      return const_cast<DeclSpec&>(declarator.getDeclSpec());
204218893Sdim    }
205218893Sdim
206218893Sdim    void restoreDeclSpecAttrs() {
207221345Sdim      assert(hasSavedAttrs);
208221345Sdim
209221345Sdim      if (savedAttrs.empty()) {
210221345Sdim        getMutableDeclSpec().getAttributes().set(0);
211221345Sdim        return;
212221345Sdim      }
213221345Sdim
214218893Sdim      getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
215218893Sdim      for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
216218893Sdim        savedAttrs[i]->setNext(savedAttrs[i+1]);
217218893Sdim      savedAttrs.back()->setNext(0);
218218893Sdim    }
219218893Sdim  };
220218893Sdim
221218893Sdim  /// Basically std::pair except that we really want to avoid an
222218893Sdim  /// implicit operator= for safety concerns.  It's also a minor
223218893Sdim  /// link-time optimization for this to be a private type.
224218893Sdim  struct AttrAndList {
225218893Sdim    /// The attribute.
226218893Sdim    AttributeList &first;
227218893Sdim
228218893Sdim    /// The head of the list the attribute is currently in.
229218893Sdim    AttributeList *&second;
230218893Sdim
231218893Sdim    AttrAndList(AttributeList &attr, AttributeList *&head)
232218893Sdim      : first(attr), second(head) {}
233218893Sdim  };
234203955Srdivacky}
235203955Srdivacky
236218893Sdimnamespace llvm {
237218893Sdim  template <> struct isPodLike<AttrAndList> {
238218893Sdim    static const bool value = true;
239218893Sdim  };
240218893Sdim}
241218893Sdim
242218893Sdimstatic void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
243218893Sdim  attr.setNext(head);
244218893Sdim  head = &attr;
245218893Sdim}
246218893Sdim
247218893Sdimstatic void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
248218893Sdim  if (head == &attr) {
249218893Sdim    head = attr.getNext();
250218893Sdim    return;
251203955Srdivacky  }
252218893Sdim
253218893Sdim  AttributeList *cur = head;
254218893Sdim  while (true) {
255218893Sdim    assert(cur && cur->getNext() && "ran out of attrs?");
256218893Sdim    if (cur->getNext() == &attr) {
257218893Sdim      cur->setNext(attr.getNext());
258218893Sdim      return;
259218893Sdim    }
260218893Sdim    cur = cur->getNext();
261218893Sdim  }
262203955Srdivacky}
263203955Srdivacky
264218893Sdimstatic void moveAttrFromListToList(AttributeList &attr,
265218893Sdim                                   AttributeList *&fromList,
266218893Sdim                                   AttributeList *&toList) {
267218893Sdim  spliceAttrOutOfList(attr, fromList);
268218893Sdim  spliceAttrIntoList(attr, toList);
269218893Sdim}
270218893Sdim
271218893Sdimstatic void processTypeAttrs(TypeProcessingState &state,
272218893Sdim                             QualType &type, bool isDeclSpec,
273218893Sdim                             AttributeList *attrs);
274218893Sdim
275218893Sdimstatic bool handleFunctionTypeAttr(TypeProcessingState &state,
276218893Sdim                                   AttributeList &attr,
277218893Sdim                                   QualType &type);
278218893Sdim
279218893Sdimstatic bool handleObjCGCTypeAttr(TypeProcessingState &state,
280218893Sdim                                 AttributeList &attr, QualType &type);
281218893Sdim
282224145Sdimstatic bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
283224145Sdim                                       AttributeList &attr, QualType &type);
284224145Sdim
285218893Sdimstatic bool handleObjCPointerTypeAttr(TypeProcessingState &state,
286218893Sdim                                      AttributeList &attr, QualType &type) {
287224145Sdim  if (attr.getKind() == AttributeList::AT_objc_gc)
288224145Sdim    return handleObjCGCTypeAttr(state, attr, type);
289224145Sdim  assert(attr.getKind() == AttributeList::AT_objc_ownership);
290224145Sdim  return handleObjCOwnershipTypeAttr(state, attr, type);
291218893Sdim}
292218893Sdim
293218893Sdim/// Given that an objc_gc attribute was written somewhere on a
294218893Sdim/// declaration *other* than on the declarator itself (for which, use
295218893Sdim/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
296218893Sdim/// didn't apply in whatever position it was written in, try to move
297218893Sdim/// it to a more appropriate position.
298218893Sdimstatic void distributeObjCPointerTypeAttr(TypeProcessingState &state,
299218893Sdim                                          AttributeList &attr,
300218893Sdim                                          QualType type) {
301218893Sdim  Declarator &declarator = state.getDeclarator();
302218893Sdim  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
303218893Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
304218893Sdim    switch (chunk.Kind) {
305218893Sdim    case DeclaratorChunk::Pointer:
306218893Sdim    case DeclaratorChunk::BlockPointer:
307218893Sdim      moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
308218893Sdim                             chunk.getAttrListRef());
309218893Sdim      return;
310218893Sdim
311218893Sdim    case DeclaratorChunk::Paren:
312218893Sdim    case DeclaratorChunk::Array:
313218893Sdim      continue;
314218893Sdim
315218893Sdim    // Don't walk through these.
316218893Sdim    case DeclaratorChunk::Reference:
317218893Sdim    case DeclaratorChunk::Function:
318218893Sdim    case DeclaratorChunk::MemberPointer:
319218893Sdim      goto error;
320218893Sdim    }
321218893Sdim  }
322218893Sdim error:
323221345Sdim
324221345Sdim  diagnoseBadTypeAttribute(state.getSema(), attr, type);
325218893Sdim}
326218893Sdim
327218893Sdim/// Distribute an objc_gc type attribute that was written on the
328218893Sdim/// declarator.
329218893Sdimstatic void
330218893SdimdistributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
331218893Sdim                                            AttributeList &attr,
332218893Sdim                                            QualType &declSpecType) {
333218893Sdim  Declarator &declarator = state.getDeclarator();
334218893Sdim
335218893Sdim  // objc_gc goes on the innermost pointer to something that's not a
336218893Sdim  // pointer.
337218893Sdim  unsigned innermost = -1U;
338218893Sdim  bool considerDeclSpec = true;
339218893Sdim  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
340218893Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(i);
341218893Sdim    switch (chunk.Kind) {
342218893Sdim    case DeclaratorChunk::Pointer:
343218893Sdim    case DeclaratorChunk::BlockPointer:
344218893Sdim      innermost = i;
345218893Sdim      continue;
346218893Sdim
347218893Sdim    case DeclaratorChunk::Reference:
348218893Sdim    case DeclaratorChunk::MemberPointer:
349218893Sdim    case DeclaratorChunk::Paren:
350218893Sdim    case DeclaratorChunk::Array:
351218893Sdim      continue;
352218893Sdim
353218893Sdim    case DeclaratorChunk::Function:
354218893Sdim      considerDeclSpec = false;
355218893Sdim      goto done;
356218893Sdim    }
357218893Sdim  }
358218893Sdim done:
359218893Sdim
360218893Sdim  // That might actually be the decl spec if we weren't blocked by
361218893Sdim  // anything in the declarator.
362218893Sdim  if (considerDeclSpec) {
363221345Sdim    if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
364221345Sdim      // Splice the attribute into the decl spec.  Prevents the
365221345Sdim      // attribute from being applied multiple times and gives
366221345Sdim      // the source-location-filler something to work with.
367221345Sdim      state.saveDeclSpecAttrs();
368221345Sdim      moveAttrFromListToList(attr, declarator.getAttrListRef(),
369221345Sdim               declarator.getMutableDeclSpec().getAttributes().getListRef());
370218893Sdim      return;
371221345Sdim    }
372218893Sdim  }
373218893Sdim
374218893Sdim  // Otherwise, if we found an appropriate chunk, splice the attribute
375218893Sdim  // into it.
376218893Sdim  if (innermost != -1U) {
377218893Sdim    moveAttrFromListToList(attr, declarator.getAttrListRef(),
378218893Sdim                       declarator.getTypeObject(innermost).getAttrListRef());
379218893Sdim    return;
380218893Sdim  }
381218893Sdim
382218893Sdim  // Otherwise, diagnose when we're done building the type.
383218893Sdim  spliceAttrOutOfList(attr, declarator.getAttrListRef());
384218893Sdim  state.addIgnoredTypeAttr(attr);
385218893Sdim}
386218893Sdim
387218893Sdim/// A function type attribute was written somewhere in a declaration
388218893Sdim/// *other* than on the declarator itself or in the decl spec.  Given
389218893Sdim/// that it didn't apply in whatever position it was written in, try
390218893Sdim/// to move it to a more appropriate position.
391218893Sdimstatic void distributeFunctionTypeAttr(TypeProcessingState &state,
392218893Sdim                                       AttributeList &attr,
393218893Sdim                                       QualType type) {
394218893Sdim  Declarator &declarator = state.getDeclarator();
395218893Sdim
396218893Sdim  // Try to push the attribute from the return type of a function to
397218893Sdim  // the function itself.
398218893Sdim  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
399218893Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
400218893Sdim    switch (chunk.Kind) {
401218893Sdim    case DeclaratorChunk::Function:
402218893Sdim      moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
403218893Sdim                             chunk.getAttrListRef());
404218893Sdim      return;
405218893Sdim
406218893Sdim    case DeclaratorChunk::Paren:
407218893Sdim    case DeclaratorChunk::Pointer:
408218893Sdim    case DeclaratorChunk::BlockPointer:
409218893Sdim    case DeclaratorChunk::Array:
410218893Sdim    case DeclaratorChunk::Reference:
411218893Sdim    case DeclaratorChunk::MemberPointer:
412218893Sdim      continue;
413218893Sdim    }
414218893Sdim  }
415218893Sdim
416221345Sdim  diagnoseBadTypeAttribute(state.getSema(), attr, type);
417218893Sdim}
418218893Sdim
419218893Sdim/// Try to distribute a function type attribute to the innermost
420218893Sdim/// function chunk or type.  Returns true if the attribute was
421218893Sdim/// distributed, false if no location was found.
422218893Sdimstatic bool
423218893SdimdistributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
424218893Sdim                                      AttributeList &attr,
425218893Sdim                                      AttributeList *&attrList,
426218893Sdim                                      QualType &declSpecType) {
427218893Sdim  Declarator &declarator = state.getDeclarator();
428218893Sdim
429218893Sdim  // Put it on the innermost function chunk, if there is one.
430218893Sdim  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
431218893Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(i);
432218893Sdim    if (chunk.Kind != DeclaratorChunk::Function) continue;
433218893Sdim
434218893Sdim    moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
435218893Sdim    return true;
436218893Sdim  }
437218893Sdim
438224145Sdim  if (handleFunctionTypeAttr(state, attr, declSpecType)) {
439224145Sdim    spliceAttrOutOfList(attr, attrList);
440224145Sdim    return true;
441224145Sdim  }
442224145Sdim
443224145Sdim  return false;
444218893Sdim}
445218893Sdim
446218893Sdim/// A function type attribute was written in the decl spec.  Try to
447218893Sdim/// apply it somewhere.
448218893Sdimstatic void
449218893SdimdistributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
450218893Sdim                                       AttributeList &attr,
451218893Sdim                                       QualType &declSpecType) {
452218893Sdim  state.saveDeclSpecAttrs();
453218893Sdim
454218893Sdim  // Try to distribute to the innermost.
455218893Sdim  if (distributeFunctionTypeAttrToInnermost(state, attr,
456218893Sdim                                            state.getCurrentAttrListRef(),
457218893Sdim                                            declSpecType))
458218893Sdim    return;
459218893Sdim
460218893Sdim  // If that failed, diagnose the bad attribute when the declarator is
461218893Sdim  // fully built.
462218893Sdim  state.addIgnoredTypeAttr(attr);
463218893Sdim}
464218893Sdim
465218893Sdim/// A function type attribute was written on the declarator.  Try to
466218893Sdim/// apply it somewhere.
467218893Sdimstatic void
468218893SdimdistributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
469218893Sdim                                         AttributeList &attr,
470218893Sdim                                         QualType &declSpecType) {
471218893Sdim  Declarator &declarator = state.getDeclarator();
472218893Sdim
473218893Sdim  // Try to distribute to the innermost.
474218893Sdim  if (distributeFunctionTypeAttrToInnermost(state, attr,
475218893Sdim                                            declarator.getAttrListRef(),
476218893Sdim                                            declSpecType))
477218893Sdim    return;
478218893Sdim
479218893Sdim  // If that failed, diagnose the bad attribute when the declarator is
480218893Sdim  // fully built.
481218893Sdim  spliceAttrOutOfList(attr, declarator.getAttrListRef());
482218893Sdim  state.addIgnoredTypeAttr(attr);
483218893Sdim}
484218893Sdim
485218893Sdim/// \brief Given that there are attributes written on the declarator
486218893Sdim/// itself, try to distribute any type attributes to the appropriate
487218893Sdim/// declarator chunk.
488218893Sdim///
489218893Sdim/// These are attributes like the following:
490218893Sdim///   int f ATTR;
491218893Sdim///   int (f ATTR)();
492218893Sdim/// but not necessarily this:
493218893Sdim///   int f() ATTR;
494218893Sdimstatic void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
495218893Sdim                                              QualType &declSpecType) {
496218893Sdim  // Collect all the type attributes from the declarator itself.
497218893Sdim  assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
498218893Sdim  AttributeList *attr = state.getDeclarator().getAttributes();
499218893Sdim  AttributeList *next;
500218893Sdim  do {
501218893Sdim    next = attr->getNext();
502218893Sdim
503218893Sdim    switch (attr->getKind()) {
504218893Sdim    OBJC_POINTER_TYPE_ATTRS_CASELIST:
505218893Sdim      distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
506218893Sdim      break;
507218893Sdim
508224145Sdim    case AttributeList::AT_ns_returns_retained:
509234353Sdim      if (!state.getSema().getLangOpts().ObjCAutoRefCount)
510224145Sdim        break;
511224145Sdim      // fallthrough
512224145Sdim
513218893Sdim    FUNCTION_TYPE_ATTRS_CASELIST:
514218893Sdim      distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
515218893Sdim      break;
516218893Sdim
517218893Sdim    default:
518218893Sdim      break;
519218893Sdim    }
520218893Sdim  } while ((attr = next));
521218893Sdim}
522218893Sdim
523218893Sdim/// Add a synthetic '()' to a block-literal declarator if it is
524218893Sdim/// required, given the return type.
525218893Sdimstatic void maybeSynthesizeBlockSignature(TypeProcessingState &state,
526218893Sdim                                          QualType declSpecType) {
527218893Sdim  Declarator &declarator = state.getDeclarator();
528218893Sdim
529218893Sdim  // First, check whether the declarator would produce a function,
530218893Sdim  // i.e. whether the innermost semantic chunk is a function.
531218893Sdim  if (declarator.isFunctionDeclarator()) {
532218893Sdim    // If so, make that declarator a prototyped declarator.
533218893Sdim    declarator.getFunctionTypeInfo().hasPrototype = true;
534218893Sdim    return;
535218893Sdim  }
536218893Sdim
537218893Sdim  // If there are any type objects, the type as written won't name a
538218893Sdim  // function, regardless of the decl spec type.  This is because a
539218893Sdim  // block signature declarator is always an abstract-declarator, and
540218893Sdim  // abstract-declarators can't just be parentheses chunks.  Therefore
541218893Sdim  // we need to build a function chunk unless there are no type
542218893Sdim  // objects and the decl spec type is a function.
543218893Sdim  if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
544218893Sdim    return;
545218893Sdim
546218893Sdim  // Note that there *are* cases with invalid declarators where
547218893Sdim  // declarators consist solely of parentheses.  In general, these
548218893Sdim  // occur only in failed efforts to make function declarators, so
549218893Sdim  // faking up the function chunk is still the right thing to do.
550218893Sdim
551218893Sdim  // Otherwise, we need to fake up a function declarator.
552234353Sdim  SourceLocation loc = declarator.getLocStart();
553218893Sdim
554218893Sdim  // ...and *prepend* it to the declarator.
555218893Sdim  declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
556218893Sdim                             /*proto*/ true,
557218893Sdim                             /*variadic*/ false, SourceLocation(),
558218893Sdim                             /*args*/ 0, 0,
559218893Sdim                             /*type quals*/ 0,
560218893Sdim                             /*ref-qualifier*/true, SourceLocation(),
561234353Sdim                             /*const qualifier*/SourceLocation(),
562234353Sdim                             /*volatile qualifier*/SourceLocation(),
563224145Sdim                             /*mutable qualifier*/SourceLocation(),
564235864Sdim                             /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
565218893Sdim                             /*parens*/ loc, loc,
566218893Sdim                             declarator));
567218893Sdim
568218893Sdim  // For consistency, make sure the state still has us as processing
569218893Sdim  // the decl spec.
570218893Sdim  assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
571218893Sdim  state.setCurrentChunkIndex(declarator.getNumTypeObjects());
572218893Sdim}
573218893Sdim
574193326Sed/// \brief Convert the specified declspec to the appropriate type
575193326Sed/// object.
576198893Srdivacky/// \param D  the declarator containing the declaration specifier.
577193326Sed/// \returns The type described by the declaration specifiers.  This function
578193326Sed/// never returns null.
579224145Sdimstatic QualType ConvertDeclSpecToType(TypeProcessingState &state) {
580193326Sed  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
581193326Sed  // checking.
582218893Sdim
583224145Sdim  Sema &S = state.getSema();
584218893Sdim  Declarator &declarator = state.getDeclarator();
585218893Sdim  const DeclSpec &DS = declarator.getDeclSpec();
586218893Sdim  SourceLocation DeclLoc = declarator.getIdentifierLoc();
587198893Srdivacky  if (DeclLoc.isInvalid())
588234353Sdim    DeclLoc = DS.getLocStart();
589198893Srdivacky
590218893Sdim  ASTContext &Context = S.Context;
591198893Srdivacky
592193326Sed  QualType Result;
593193326Sed  switch (DS.getTypeSpecType()) {
594193326Sed  case DeclSpec::TST_void:
595193326Sed    Result = Context.VoidTy;
596193326Sed    break;
597193326Sed  case DeclSpec::TST_char:
598193326Sed    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
599193326Sed      Result = Context.CharTy;
600193326Sed    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
601193326Sed      Result = Context.SignedCharTy;
602193326Sed    else {
603193326Sed      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
604193326Sed             "Unknown TSS value");
605193326Sed      Result = Context.UnsignedCharTy;
606193326Sed    }
607193326Sed    break;
608193326Sed  case DeclSpec::TST_wchar:
609193326Sed    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
610193326Sed      Result = Context.WCharTy;
611193326Sed    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
612218893Sdim      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
613193326Sed        << DS.getSpecifierName(DS.getTypeSpecType());
614193326Sed      Result = Context.getSignedWCharType();
615193326Sed    } else {
616193326Sed      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
617193326Sed        "Unknown TSS value");
618218893Sdim      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
619193326Sed        << DS.getSpecifierName(DS.getTypeSpecType());
620193326Sed      Result = Context.getUnsignedWCharType();
621193326Sed    }
622193326Sed    break;
623198092Srdivacky  case DeclSpec::TST_char16:
624198092Srdivacky      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
625198092Srdivacky        "Unknown TSS value");
626198092Srdivacky      Result = Context.Char16Ty;
627198092Srdivacky    break;
628198092Srdivacky  case DeclSpec::TST_char32:
629198092Srdivacky      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
630198092Srdivacky        "Unknown TSS value");
631198092Srdivacky      Result = Context.Char32Ty;
632198092Srdivacky    break;
633193326Sed  case DeclSpec::TST_unspecified:
634193326Sed    // "<proto1,proto2>" is an objc qualified ID with a missing id.
635193326Sed    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
636208600Srdivacky      Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
637208600Srdivacky                                         (ObjCProtocolDecl**)PQ,
638208600Srdivacky                                         DS.getNumProtocolQualifiers());
639208600Srdivacky      Result = Context.getObjCObjectPointerType(Result);
640193326Sed      break;
641193326Sed    }
642198893Srdivacky
643198893Srdivacky    // If this is a missing declspec in a block literal return context, then it
644198893Srdivacky    // is inferred from the return statements inside the block.
645234353Sdim    // The declspec is always missing in a lambda expr context; it is either
646234353Sdim    // specified with a trailing return type or inferred.
647234353Sdim    if (declarator.getContext() == Declarator::LambdaExprContext ||
648234353Sdim        isOmittedBlockReturnType(declarator)) {
649198893Srdivacky      Result = Context.DependentTy;
650198893Srdivacky      break;
651198893Srdivacky    }
652198092Srdivacky
653193326Sed    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
654193326Sed    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
655193326Sed    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
656193326Sed    // Note that the one exception to this is function definitions, which are
657193326Sed    // allowed to be completely missing a declspec.  This is handled in the
658193326Sed    // parser already though by it pretending to have seen an 'int' in this
659193326Sed    // case.
660234353Sdim    if (S.getLangOpts().ImplicitInt) {
661193326Sed      // In C89 mode, we only warn if there is a completely missing declspec
662193326Sed      // when one is not allowed.
663193326Sed      if (DS.isEmpty()) {
664218893Sdim        S.Diag(DeclLoc, diag::ext_missing_declspec)
665193326Sed          << DS.getSourceRange()
666234353Sdim        << FixItHint::CreateInsertion(DS.getLocStart(), "int");
667193326Sed      }
668193326Sed    } else if (!DS.hasTypeSpecifier()) {
669193326Sed      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
670193326Sed      // "At least one type specifier shall be given in the declaration
671193326Sed      // specifiers in each declaration, and in the specifier-qualifier list in
672193326Sed      // each struct declaration and type name."
673193326Sed      // FIXME: Does Microsoft really have the implicit int extension in C++?
674234353Sdim      if (S.getLangOpts().CPlusPlus &&
675234353Sdim          !S.getLangOpts().MicrosoftExt) {
676218893Sdim        S.Diag(DeclLoc, diag::err_missing_type_specifier)
677193326Sed          << DS.getSourceRange();
678198092Srdivacky
679195099Sed        // When this occurs in C++ code, often something is very broken with the
680195099Sed        // value being declared, poison it as invalid so we don't get chains of
681195099Sed        // errors.
682218893Sdim        declarator.setInvalidType(true);
683195099Sed      } else {
684218893Sdim        S.Diag(DeclLoc, diag::ext_missing_type_specifier)
685193326Sed          << DS.getSourceRange();
686195099Sed      }
687193326Sed    }
688198092Srdivacky
689198092Srdivacky    // FALL THROUGH.
690193326Sed  case DeclSpec::TST_int: {
691193326Sed    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
692193326Sed      switch (DS.getTypeSpecWidth()) {
693193326Sed      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
694193326Sed      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
695193326Sed      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
696198893Srdivacky      case DeclSpec::TSW_longlong:
697198893Srdivacky        Result = Context.LongLongTy;
698198893Srdivacky
699198893Srdivacky        // long long is a C99 feature.
700234353Sdim        if (!S.getLangOpts().C99)
701234353Sdim          S.Diag(DS.getTypeSpecWidthLoc(),
702234353Sdim                 S.getLangOpts().CPlusPlus0x ?
703234353Sdim                   diag::warn_cxx98_compat_longlong : diag::ext_longlong);
704198893Srdivacky        break;
705193326Sed      }
706193326Sed    } else {
707193326Sed      switch (DS.getTypeSpecWidth()) {
708193326Sed      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
709193326Sed      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
710193326Sed      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
711198893Srdivacky      case DeclSpec::TSW_longlong:
712198893Srdivacky        Result = Context.UnsignedLongLongTy;
713198893Srdivacky
714198893Srdivacky        // long long is a C99 feature.
715234353Sdim        if (!S.getLangOpts().C99)
716234353Sdim          S.Diag(DS.getTypeSpecWidthLoc(),
717234353Sdim                 S.getLangOpts().CPlusPlus0x ?
718234353Sdim                   diag::warn_cxx98_compat_longlong : diag::ext_longlong);
719198893Srdivacky        break;
720193326Sed      }
721193326Sed    }
722193326Sed    break;
723193326Sed  }
724234353Sdim  case DeclSpec::TST_int128:
725234353Sdim    if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
726234353Sdim      Result = Context.UnsignedInt128Ty;
727234353Sdim    else
728234353Sdim      Result = Context.Int128Ty;
729234353Sdim    break;
730226633Sdim  case DeclSpec::TST_half: Result = Context.HalfTy; break;
731193326Sed  case DeclSpec::TST_float: Result = Context.FloatTy; break;
732193326Sed  case DeclSpec::TST_double:
733193326Sed    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
734193326Sed      Result = Context.LongDoubleTy;
735193326Sed    else
736193326Sed      Result = Context.DoubleTy;
737218893Sdim
738234353Sdim    if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
739218893Sdim      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
740218893Sdim      declarator.setInvalidType(true);
741218893Sdim    }
742193326Sed    break;
743193326Sed  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
744193326Sed  case DeclSpec::TST_decimal32:    // _Decimal32
745193326Sed  case DeclSpec::TST_decimal64:    // _Decimal64
746193326Sed  case DeclSpec::TST_decimal128:   // _Decimal128
747218893Sdim    S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
748193326Sed    Result = Context.IntTy;
749218893Sdim    declarator.setInvalidType(true);
750193326Sed    break;
751193326Sed  case DeclSpec::TST_class:
752193326Sed  case DeclSpec::TST_enum:
753193326Sed  case DeclSpec::TST_union:
754193326Sed  case DeclSpec::TST_struct: {
755212904Sdim    TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
756198092Srdivacky    if (!D) {
757198092Srdivacky      // This can happen in C++ with ambiguous lookups.
758198092Srdivacky      Result = Context.IntTy;
759218893Sdim      declarator.setInvalidType(true);
760198092Srdivacky      break;
761198092Srdivacky    }
762198092Srdivacky
763198893Srdivacky    // If the type is deprecated or unavailable, diagnose it.
764221345Sdim    S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
765198893Srdivacky
766193326Sed    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
767198893Srdivacky           DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
768198893Srdivacky
769193326Sed    // TypeQuals handled by caller.
770198893Srdivacky    Result = Context.getTypeDeclType(D);
771198092Srdivacky
772221345Sdim    // In both C and C++, make an ElaboratedType.
773221345Sdim    ElaboratedTypeKeyword Keyword
774221345Sdim      = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
775221345Sdim    Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
776193326Sed    break;
777198092Srdivacky  }
778193326Sed  case DeclSpec::TST_typename: {
779193326Sed    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
780193326Sed           DS.getTypeSpecSign() == 0 &&
781193326Sed           "Can't handle qualifiers on typedef names yet!");
782218893Sdim    Result = S.GetTypeFromParser(DS.getRepAsType());
783212904Sdim    if (Result.isNull())
784218893Sdim      declarator.setInvalidType(true);
785212904Sdim    else if (DeclSpec::ProtocolQualifierListTy PQ
786212904Sdim               = DS.getProtocolQualifiers()) {
787208600Srdivacky      if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
788208600Srdivacky        // Silently drop any existing protocol qualifiers.
789208600Srdivacky        // TODO: determine whether that's the right thing to do.
790208600Srdivacky        if (ObjT->getNumProtocols())
791208600Srdivacky          Result = ObjT->getBaseType();
792208600Srdivacky
793208600Srdivacky        if (DS.getNumProtocolQualifiers())
794208600Srdivacky          Result = Context.getObjCObjectType(Result,
795208600Srdivacky                                             (ObjCProtocolDecl**) PQ,
796208600Srdivacky                                             DS.getNumProtocolQualifiers());
797208600Srdivacky      } else if (Result->isObjCIdType()) {
798193326Sed        // id<protocol-list>
799208600Srdivacky        Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
800208600Srdivacky                                           (ObjCProtocolDecl**) PQ,
801208600Srdivacky                                           DS.getNumProtocolQualifiers());
802208600Srdivacky        Result = Context.getObjCObjectPointerType(Result);
803208600Srdivacky      } else if (Result->isObjCClassType()) {
804193326Sed        // Class<protocol-list>
805208600Srdivacky        Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
806208600Srdivacky                                           (ObjCProtocolDecl**) PQ,
807208600Srdivacky                                           DS.getNumProtocolQualifiers());
808208600Srdivacky        Result = Context.getObjCObjectPointerType(Result);
809193326Sed      } else {
810218893Sdim        S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
811193326Sed          << DS.getSourceRange();
812218893Sdim        declarator.setInvalidType(true);
813193326Sed      }
814193326Sed    }
815198092Srdivacky
816193326Sed    // TypeQuals handled by caller.
817193326Sed    break;
818193326Sed  }
819193326Sed  case DeclSpec::TST_typeofType:
820198092Srdivacky    // FIXME: Preserve type source info.
821218893Sdim    Result = S.GetTypeFromParser(DS.getRepAsType());
822193326Sed    assert(!Result.isNull() && "Didn't get a type for typeof?");
823218893Sdim    if (!Result->isDependentType())
824218893Sdim      if (const TagType *TT = Result->getAs<TagType>())
825218893Sdim        S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
826193326Sed    // TypeQuals handled by caller.
827193326Sed    Result = Context.getTypeOfType(Result);
828193326Sed    break;
829193326Sed  case DeclSpec::TST_typeofExpr: {
830212904Sdim    Expr *E = DS.getRepAsExpr();
831193326Sed    assert(E && "Didn't get an expression for typeof?");
832193326Sed    // TypeQuals handled by caller.
833218893Sdim    Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
834201361Srdivacky    if (Result.isNull()) {
835201361Srdivacky      Result = Context.IntTy;
836218893Sdim      declarator.setInvalidType(true);
837201361Srdivacky    }
838193326Sed    break;
839193326Sed  }
840195099Sed  case DeclSpec::TST_decltype: {
841212904Sdim    Expr *E = DS.getRepAsExpr();
842195099Sed    assert(E && "Didn't get an expression for decltype?");
843195099Sed    // TypeQuals handled by caller.
844218893Sdim    Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
845195341Sed    if (Result.isNull()) {
846195341Sed      Result = Context.IntTy;
847218893Sdim      declarator.setInvalidType(true);
848195341Sed    }
849195099Sed    break;
850195099Sed  }
851223017Sdim  case DeclSpec::TST_underlyingType:
852223017Sdim    Result = S.GetTypeFromParser(DS.getRepAsType());
853223017Sdim    assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
854223017Sdim    Result = S.BuildUnaryTransformType(Result,
855223017Sdim                                       UnaryTransformType::EnumUnderlyingType,
856223017Sdim                                       DS.getTypeSpecTypeLoc());
857223017Sdim    if (Result.isNull()) {
858223017Sdim      Result = Context.IntTy;
859223017Sdim      declarator.setInvalidType(true);
860223017Sdim    }
861223017Sdim    break;
862223017Sdim
863195099Sed  case DeclSpec::TST_auto: {
864195099Sed    // TypeQuals handled by caller.
865218893Sdim    Result = Context.getAutoType(QualType());
866195099Sed    break;
867195099Sed  }
868198092Srdivacky
869221345Sdim  case DeclSpec::TST_unknown_anytype:
870221345Sdim    Result = Context.UnknownAnyTy;
871221345Sdim    break;
872221345Sdim
873226633Sdim  case DeclSpec::TST_atomic:
874226633Sdim    Result = S.GetTypeFromParser(DS.getRepAsType());
875226633Sdim    assert(!Result.isNull() && "Didn't get a type for _Atomic?");
876226633Sdim    Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
877226633Sdim    if (Result.isNull()) {
878226633Sdim      Result = Context.IntTy;
879226633Sdim      declarator.setInvalidType(true);
880226633Sdim    }
881226633Sdim    break;
882226633Sdim
883193326Sed  case DeclSpec::TST_error:
884193326Sed    Result = Context.IntTy;
885218893Sdim    declarator.setInvalidType(true);
886193326Sed    break;
887193326Sed  }
888198092Srdivacky
889193326Sed  // Handle complex types.
890193326Sed  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
891234353Sdim    if (S.getLangOpts().Freestanding)
892218893Sdim      S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
893193326Sed    Result = Context.getComplexType(Result);
894203955Srdivacky  } else if (DS.isTypeAltiVecVector()) {
895203955Srdivacky    unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
896203955Srdivacky    assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
897218893Sdim    VectorType::VectorKind VecKind = VectorType::AltiVecVector;
898210299Sed    if (DS.isTypeAltiVecPixel())
899218893Sdim      VecKind = VectorType::AltiVecPixel;
900210299Sed    else if (DS.isTypeAltiVecBool())
901218893Sdim      VecKind = VectorType::AltiVecBool;
902218893Sdim    Result = Context.getVectorType(Result, 128/typeSize, VecKind);
903193326Sed  }
904198092Srdivacky
905218893Sdim  // FIXME: Imaginary.
906218893Sdim  if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
907218893Sdim    S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
908198092Srdivacky
909218893Sdim  // Before we process any type attributes, synthesize a block literal
910218893Sdim  // function declarator if necessary.
911218893Sdim  if (declarator.getContext() == Declarator::BlockLiteralContext)
912218893Sdim    maybeSynthesizeBlockSignature(state, Result);
913198092Srdivacky
914218893Sdim  // Apply any type attributes from the decl spec.  This may cause the
915218893Sdim  // list of type attributes to be temporarily saved while the type
916218893Sdim  // attributes are pushed around.
917218893Sdim  if (AttributeList *attrs = DS.getAttributes().getList())
918218893Sdim    processTypeAttrs(state, Result, true, attrs);
919218893Sdim
920193326Sed  // Apply const/volatile/restrict qualifiers to T.
921193326Sed  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
922193326Sed
923193326Sed    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
924193326Sed    // or incomplete types shall not be restrict-qualified."  C++ also allows
925193326Sed    // restrict-qualified references.
926198092Srdivacky    if (TypeQuals & DeclSpec::TQ_restrict) {
927200583Srdivacky      if (Result->isAnyPointerType() || Result->isReferenceType()) {
928200583Srdivacky        QualType EltTy;
929200583Srdivacky        if (Result->isObjCObjectPointerType())
930200583Srdivacky          EltTy = Result;
931200583Srdivacky        else
932200583Srdivacky          EltTy = Result->isPointerType() ?
933200583Srdivacky                    Result->getAs<PointerType>()->getPointeeType() :
934200583Srdivacky                    Result->getAs<ReferenceType>()->getPointeeType();
935198092Srdivacky
936193326Sed        // If we have a pointer or reference, the pointee must have an object
937193326Sed        // incomplete type.
938193326Sed        if (!EltTy->isIncompleteOrObjectType()) {
939218893Sdim          S.Diag(DS.getRestrictSpecLoc(),
940193326Sed               diag::err_typecheck_invalid_restrict_invalid_pointee)
941193326Sed            << EltTy << DS.getSourceRange();
942198092Srdivacky          TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
943193326Sed        }
944193326Sed      } else {
945218893Sdim        S.Diag(DS.getRestrictSpecLoc(),
946218893Sdim               diag::err_typecheck_invalid_restrict_not_pointer)
947193326Sed          << Result << DS.getSourceRange();
948198092Srdivacky        TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
949193326Sed      }
950193326Sed    }
951198092Srdivacky
952193326Sed    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
953193326Sed    // of a function type includes any type qualifiers, the behavior is
954193326Sed    // undefined."
955193326Sed    if (Result->isFunctionType() && TypeQuals) {
956193326Sed      // Get some location to point at, either the C or V location.
957193326Sed      SourceLocation Loc;
958198092Srdivacky      if (TypeQuals & DeclSpec::TQ_const)
959193326Sed        Loc = DS.getConstSpecLoc();
960198092Srdivacky      else if (TypeQuals & DeclSpec::TQ_volatile)
961198092Srdivacky        Loc = DS.getVolatileSpecLoc();
962193326Sed      else {
963198092Srdivacky        assert((TypeQuals & DeclSpec::TQ_restrict) &&
964198092Srdivacky               "Has CVR quals but not C, V, or R?");
965198092Srdivacky        Loc = DS.getRestrictSpecLoc();
966193326Sed      }
967218893Sdim      S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
968193326Sed        << Result << DS.getSourceRange();
969193326Sed    }
970198092Srdivacky
971193326Sed    // C++ [dcl.ref]p1:
972193326Sed    //   Cv-qualified references are ill-formed except when the
973193326Sed    //   cv-qualifiers are introduced through the use of a typedef
974193326Sed    //   (7.1.3) or of a template type argument (14.3), in which
975193326Sed    //   case the cv-qualifiers are ignored.
976193326Sed    // FIXME: Shouldn't we be checking SCS_typedef here?
977193326Sed    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
978193326Sed        TypeQuals && Result->isReferenceType()) {
979198092Srdivacky      TypeQuals &= ~DeclSpec::TQ_const;
980198092Srdivacky      TypeQuals &= ~DeclSpec::TQ_volatile;
981198092Srdivacky    }
982198092Srdivacky
983234353Sdim    // C90 6.5.3 constraints: "The same type qualifier shall not appear more
984234353Sdim    // than once in the same specifier-list or qualifier-list, either directly
985234353Sdim    // or via one or more typedefs."
986234353Sdim    if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
987234353Sdim        && TypeQuals & Result.getCVRQualifiers()) {
988234353Sdim      if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
989234353Sdim        S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
990234353Sdim          << "const";
991234353Sdim      }
992234353Sdim
993234353Sdim      if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
994234353Sdim        S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
995234353Sdim          << "volatile";
996234353Sdim      }
997234353Sdim
998234353Sdim      // C90 doesn't have restrict, so it doesn't force us to produce a warning
999234353Sdim      // in this case.
1000234353Sdim    }
1001234353Sdim
1002198092Srdivacky    Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
1003198092Srdivacky    Result = Context.getQualifiedType(Result, Quals);
1004193326Sed  }
1005198092Srdivacky
1006193326Sed  return Result;
1007193326Sed}
1008193326Sed
1009193326Sedstatic std::string getPrintableNameForEntity(DeclarationName Entity) {
1010193326Sed  if (Entity)
1011193326Sed    return Entity.getAsString();
1012198092Srdivacky
1013193326Sed  return "type name";
1014193326Sed}
1015193326Sed
1016210299SedQualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1017210299Sed                                  Qualifiers Qs) {
1018210299Sed  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1019210299Sed  // object or incomplete types shall not be restrict-qualified."
1020210299Sed  if (Qs.hasRestrict()) {
1021210299Sed    unsigned DiagID = 0;
1022210299Sed    QualType ProblemTy;
1023210299Sed
1024210299Sed    const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
1025210299Sed    if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
1026210299Sed      if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
1027210299Sed        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1028210299Sed        ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
1029210299Sed      }
1030210299Sed    } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1031210299Sed      if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1032210299Sed        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1033210299Sed        ProblemTy = T->getAs<PointerType>()->getPointeeType();
1034210299Sed      }
1035210299Sed    } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
1036210299Sed      if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1037210299Sed        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1038210299Sed        ProblemTy = T->getAs<PointerType>()->getPointeeType();
1039210299Sed      }
1040210299Sed    } else if (!Ty->isDependentType()) {
1041210299Sed      // FIXME: this deserves a proper diagnostic
1042210299Sed      DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1043210299Sed      ProblemTy = T;
1044210299Sed    }
1045210299Sed
1046210299Sed    if (DiagID) {
1047210299Sed      Diag(Loc, DiagID) << ProblemTy;
1048210299Sed      Qs.removeRestrict();
1049210299Sed    }
1050210299Sed  }
1051210299Sed
1052210299Sed  return Context.getQualifiedType(T, Qs);
1053210299Sed}
1054210299Sed
1055218893Sdim/// \brief Build a paren type including \p T.
1056218893SdimQualType Sema::BuildParenType(QualType T) {
1057218893Sdim  return Context.getParenType(T);
1058218893Sdim}
1059218893Sdim
1060224145Sdim/// Given that we're building a pointer or reference to the given
1061224145Sdimstatic QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1062224145Sdim                                           SourceLocation loc,
1063224145Sdim                                           bool isReference) {
1064224145Sdim  // Bail out if retention is unrequired or already specified.
1065224145Sdim  if (!type->isObjCLifetimeType() ||
1066224145Sdim      type.getObjCLifetime() != Qualifiers::OCL_None)
1067224145Sdim    return type;
1068224145Sdim
1069224145Sdim  Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1070224145Sdim
1071224145Sdim  // If the object type is const-qualified, we can safely use
1072224145Sdim  // __unsafe_unretained.  This is safe (because there are no read
1073224145Sdim  // barriers), and it'll be safe to coerce anything but __weak* to
1074224145Sdim  // the resulting type.
1075224145Sdim  if (type.isConstQualified()) {
1076224145Sdim    implicitLifetime = Qualifiers::OCL_ExplicitNone;
1077224145Sdim
1078224145Sdim  // Otherwise, check whether the static type does not require
1079224145Sdim  // retaining.  This currently only triggers for Class (possibly
1080224145Sdim  // protocol-qualifed, and arrays thereof).
1081224145Sdim  } else if (type->isObjCARCImplicitlyUnretainedType()) {
1082224145Sdim    implicitLifetime = Qualifiers::OCL_ExplicitNone;
1083224145Sdim
1084234353Sdim  // If we are in an unevaluated context, like sizeof, skip adding a
1085234353Sdim  // qualification.
1086226633Sdim  } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) {
1087234353Sdim    return type;
1088226633Sdim
1089234353Sdim  // If that failed, give an error and recover using __strong.  __strong
1090234353Sdim  // is the option most likely to prevent spurious second-order diagnostics,
1091234353Sdim  // like when binding a reference to a field.
1092224145Sdim  } else {
1093224145Sdim    // These types can show up in private ivars in system headers, so
1094224145Sdim    // we need this to not be an error in those cases.  Instead we
1095224145Sdim    // want to delay.
1096224145Sdim    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1097224145Sdim      S.DelayedDiagnostics.add(
1098224145Sdim          sema::DelayedDiagnostic::makeForbiddenType(loc,
1099224145Sdim              diag::err_arc_indirect_no_ownership, type, isReference));
1100224145Sdim    } else {
1101224145Sdim      S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1102224145Sdim    }
1103234353Sdim    implicitLifetime = Qualifiers::OCL_Strong;
1104224145Sdim  }
1105224145Sdim  assert(implicitLifetime && "didn't infer any lifetime!");
1106224145Sdim
1107224145Sdim  Qualifiers qs;
1108224145Sdim  qs.addObjCLifetime(implicitLifetime);
1109224145Sdim  return S.Context.getQualifiedType(type, qs);
1110224145Sdim}
1111224145Sdim
1112193326Sed/// \brief Build a pointer type.
1113193326Sed///
1114193326Sed/// \param T The type to which we'll be building a pointer.
1115193326Sed///
1116193326Sed/// \param Loc The location of the entity whose type involves this
1117193326Sed/// pointer type or, if there is no such entity, the location of the
1118193326Sed/// type that will have pointer type.
1119193326Sed///
1120193326Sed/// \param Entity The name of the entity that involves the pointer
1121193326Sed/// type, if known.
1122193326Sed///
1123193326Sed/// \returns A suitable pointer type, if there are no
1124193326Sed/// errors. Otherwise, returns a NULL type.
1125210299SedQualType Sema::BuildPointerType(QualType T,
1126193326Sed                                SourceLocation Loc, DeclarationName Entity) {
1127193326Sed  if (T->isReferenceType()) {
1128193326Sed    // C++ 8.3.2p4: There shall be no ... pointers to references ...
1129193326Sed    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1130198893Srdivacky      << getPrintableNameForEntity(Entity) << T;
1131193326Sed    return QualType();
1132193326Sed  }
1133193326Sed
1134208600Srdivacky  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1135207619Srdivacky
1136224145Sdim  // In ARC, it is forbidden to build pointers to unqualified pointers.
1137234353Sdim  if (getLangOpts().ObjCAutoRefCount)
1138224145Sdim    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1139224145Sdim
1140193326Sed  // Build the pointer type.
1141210299Sed  return Context.getPointerType(T);
1142193326Sed}
1143193326Sed
1144193326Sed/// \brief Build a reference type.
1145193326Sed///
1146193326Sed/// \param T The type to which we'll be building a reference.
1147193326Sed///
1148193326Sed/// \param Loc The location of the entity whose type involves this
1149193326Sed/// reference type or, if there is no such entity, the location of the
1150193326Sed/// type that will have reference type.
1151193326Sed///
1152193326Sed/// \param Entity The name of the entity that involves the reference
1153193326Sed/// type, if known.
1154193326Sed///
1155193326Sed/// \returns A suitable reference type, if there are no
1156193326Sed/// errors. Otherwise, returns a NULL type.
1157198398SrdivackyQualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1158210299Sed                                  SourceLocation Loc,
1159198398Srdivacky                                  DeclarationName Entity) {
1160223017Sdim  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1161223017Sdim         "Unresolved overloaded function type");
1162223017Sdim
1163218893Sdim  // C++0x [dcl.ref]p6:
1164218893Sdim  //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1165218893Sdim  //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1166218893Sdim  //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1167218893Sdim  //   the type "lvalue reference to T", while an attempt to create the type
1168218893Sdim  //   "rvalue reference to cv TR" creates the type TR.
1169198398Srdivacky  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1170198398Srdivacky
1171198398Srdivacky  // C++ [dcl.ref]p4: There shall be no references to references.
1172198398Srdivacky  //
1173198398Srdivacky  // According to C++ DR 106, references to references are only
1174198398Srdivacky  // diagnosed when they are written directly (e.g., "int & &"),
1175198398Srdivacky  // but not when they happen via a typedef:
1176198398Srdivacky  //
1177198398Srdivacky  //   typedef int& intref;
1178198398Srdivacky  //   typedef intref& intref2;
1179198398Srdivacky  //
1180198398Srdivacky  // Parser::ParseDeclaratorInternal diagnoses the case where
1181198398Srdivacky  // references are written directly; here, we handle the
1182218893Sdim  // collapsing of references-to-references as described in C++0x.
1183218893Sdim  // DR 106 and 540 introduce reference-collapsing into C++98/03.
1184198398Srdivacky
1185193326Sed  // C++ [dcl.ref]p1:
1186198092Srdivacky  //   A declarator that specifies the type "reference to cv void"
1187193326Sed  //   is ill-formed.
1188193326Sed  if (T->isVoidType()) {
1189193326Sed    Diag(Loc, diag::err_reference_to_void);
1190193326Sed    return QualType();
1191193326Sed  }
1192193326Sed
1193224145Sdim  // In ARC, it is forbidden to build references to unqualified pointers.
1194234353Sdim  if (getLangOpts().ObjCAutoRefCount)
1195224145Sdim    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1196224145Sdim
1197193326Sed  // Handle restrict on references.
1198193326Sed  if (LValueRef)
1199210299Sed    return Context.getLValueReferenceType(T, SpelledAsLValue);
1200210299Sed  return Context.getRValueReferenceType(T);
1201193326Sed}
1202193326Sed
1203224145Sdim/// Check whether the specified array size makes the array type a VLA.  If so,
1204224145Sdim/// return true, if not, return the size of the array in SizeVal.
1205234353Sdimstatic bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1206234353Sdim  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1207234353Sdim  // (like gnu99, but not c99) accept any evaluatable value as an extension.
1208234353Sdim  return S.VerifyIntegerConstantExpression(
1209234353Sdim      ArraySize, &SizeVal, S.PDiag(), S.LangOpts.GNUMode,
1210234353Sdim      S.PDiag(diag::ext_vla_folded_to_constant)).isInvalid();
1211224145Sdim}
1212224145Sdim
1213224145Sdim
1214193326Sed/// \brief Build an array type.
1215193326Sed///
1216193326Sed/// \param T The type of each element in the array.
1217193326Sed///
1218193326Sed/// \param ASM C99 array size modifier (e.g., '*', 'static').
1219193326Sed///
1220198092Srdivacky/// \param ArraySize Expression describing the size of the array.
1221198092Srdivacky///
1222193326Sed/// \param Loc The location of the entity whose type involves this
1223193326Sed/// array type or, if there is no such entity, the location of the
1224193326Sed/// type that will have array type.
1225193326Sed///
1226193326Sed/// \param Entity The name of the entity that involves the array
1227193326Sed/// type, if known.
1228193326Sed///
1229193326Sed/// \returns A suitable array type, if there are no errors. Otherwise,
1230193326Sed/// returns a NULL type.
1231193326SedQualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1232193326Sed                              Expr *ArraySize, unsigned Quals,
1233198092Srdivacky                              SourceRange Brackets, DeclarationName Entity) {
1234198092Srdivacky
1235198092Srdivacky  SourceLocation Loc = Brackets.getBegin();
1236234353Sdim  if (getLangOpts().CPlusPlus) {
1237207619Srdivacky    // C++ [dcl.array]p1:
1238207619Srdivacky    //   T is called the array element type; this type shall not be a reference
1239207619Srdivacky    //   type, the (possibly cv-qualified) type void, a function type or an
1240207619Srdivacky    //   abstract class type.
1241207619Srdivacky    //
1242207619Srdivacky    // Note: function types are handled in the common path with C.
1243207619Srdivacky    if (T->isReferenceType()) {
1244207619Srdivacky      Diag(Loc, diag::err_illegal_decl_array_of_references)
1245207619Srdivacky      << getPrintableNameForEntity(Entity) << T;
1246207619Srdivacky      return QualType();
1247207619Srdivacky    }
1248207619Srdivacky
1249198954Srdivacky    if (T->isVoidType()) {
1250198954Srdivacky      Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1251198954Srdivacky      return QualType();
1252198954Srdivacky    }
1253207619Srdivacky
1254207619Srdivacky    if (RequireNonAbstractType(Brackets.getBegin(), T,
1255207619Srdivacky                               diag::err_array_of_abstract_type))
1256207619Srdivacky      return QualType();
1257207619Srdivacky
1258198954Srdivacky  } else {
1259207619Srdivacky    // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1260207619Srdivacky    // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1261198954Srdivacky    if (RequireCompleteType(Loc, T,
1262198954Srdivacky                            diag::err_illegal_decl_array_incomplete_type))
1263198954Srdivacky      return QualType();
1264198954Srdivacky  }
1265193326Sed
1266193326Sed  if (T->isFunctionType()) {
1267193326Sed    Diag(Loc, diag::err_illegal_decl_array_of_functions)
1268198893Srdivacky      << getPrintableNameForEntity(Entity) << T;
1269193326Sed    return QualType();
1270193326Sed  }
1271198092Srdivacky
1272218893Sdim  if (T->getContainedAutoType()) {
1273218893Sdim    Diag(Loc, diag::err_illegal_decl_array_of_auto)
1274218893Sdim      << getPrintableNameForEntity(Entity) << T;
1275195099Sed    return QualType();
1276195099Sed  }
1277198092Srdivacky
1278198092Srdivacky  if (const RecordType *EltTy = T->getAs<RecordType>()) {
1279193326Sed    // If the element type is a struct or union that contains a variadic
1280193326Sed    // array, accept it as a GNU extension: C99 6.7.2.1p2.
1281193326Sed    if (EltTy->getDecl()->hasFlexibleArrayMember())
1282193326Sed      Diag(Loc, diag::ext_flexible_array_in_array) << T;
1283208600Srdivacky  } else if (T->isObjCObjectType()) {
1284193326Sed    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1285193326Sed    return QualType();
1286193326Sed  }
1287198092Srdivacky
1288234353Sdim  // Do placeholder conversions on the array size expression.
1289234353Sdim  if (ArraySize && ArraySize->hasPlaceholderType()) {
1290234353Sdim    ExprResult Result = CheckPlaceholderExpr(ArraySize);
1291234353Sdim    if (Result.isInvalid()) return QualType();
1292234353Sdim    ArraySize = Result.take();
1293234353Sdim  }
1294234353Sdim
1295218893Sdim  // Do lvalue-to-rvalue conversions on the array size expression.
1296221345Sdim  if (ArraySize && !ArraySize->isRValue()) {
1297221345Sdim    ExprResult Result = DefaultLvalueConversion(ArraySize);
1298221345Sdim    if (Result.isInvalid())
1299221345Sdim      return QualType();
1300218893Sdim
1301221345Sdim    ArraySize = Result.take();
1302221345Sdim  }
1303221345Sdim
1304193326Sed  // C99 6.7.5.2p1: The size expression shall have integer type.
1305234353Sdim  // C++11 allows contextual conversions to such types.
1306234353Sdim  if (!getLangOpts().CPlusPlus0x &&
1307234353Sdim      ArraySize && !ArraySize->isTypeDependent() &&
1308218893Sdim      !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1309193326Sed    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1310193326Sed      << ArraySize->getType() << ArraySize->getSourceRange();
1311193326Sed    return QualType();
1312193326Sed  }
1313234353Sdim
1314212904Sdim  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1315193326Sed  if (!ArraySize) {
1316193326Sed    if (ASM == ArrayType::Star)
1317198092Srdivacky      T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1318193326Sed    else
1319193326Sed      T = Context.getIncompleteArrayType(T, ASM, Quals);
1320208600Srdivacky  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1321198092Srdivacky    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1322234353Sdim  } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1323234353Sdim              !T->isConstantSizeType()) ||
1324234353Sdim             isArraySizeVLA(*this, ArraySize, ConstVal)) {
1325234353Sdim    // Even in C++11, don't allow contextual conversions in the array bound
1326234353Sdim    // of a VLA.
1327234353Sdim    if (getLangOpts().CPlusPlus0x &&
1328234353Sdim        !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1329234353Sdim      Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1330234353Sdim        << ArraySize->getType() << ArraySize->getSourceRange();
1331234353Sdim      return QualType();
1332234353Sdim    }
1333234353Sdim
1334224145Sdim    // C99: an array with an element type that has a non-constant-size is a VLA.
1335224145Sdim    // C99: an array with a non-ICE size is a VLA.  We accept any expression
1336224145Sdim    // that we can fold to a non-zero positive value as an extension.
1337224145Sdim    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1338193326Sed  } else {
1339193326Sed    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1340193326Sed    // have a value greater than zero.
1341198954Srdivacky    if (ConstVal.isSigned() && ConstVal.isNegative()) {
1342218893Sdim      if (Entity)
1343218893Sdim        Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1344218893Sdim          << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1345218893Sdim      else
1346218893Sdim        Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1347218893Sdim          << ArraySize->getSourceRange();
1348198954Srdivacky      return QualType();
1349198092Srdivacky    }
1350198954Srdivacky    if (ConstVal == 0) {
1351206084Srdivacky      // GCC accepts zero sized static arrays. We allow them when
1352206084Srdivacky      // we're not in a SFINAE context.
1353206084Srdivacky      Diag(ArraySize->getLocStart(),
1354206084Srdivacky           isSFINAEContext()? diag::err_typecheck_zero_array_size
1355206084Srdivacky                            : diag::ext_typecheck_zero_array_size)
1356198954Srdivacky        << ArraySize->getSourceRange();
1357234353Sdim
1358234353Sdim      if (ASM == ArrayType::Static) {
1359234353Sdim        Diag(ArraySize->getLocStart(),
1360234353Sdim             diag::warn_typecheck_zero_static_array_size)
1361234353Sdim          << ArraySize->getSourceRange();
1362234353Sdim        ASM = ArrayType::Normal;
1363234353Sdim      }
1364212904Sdim    } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1365212904Sdim               !T->isIncompleteType()) {
1366212904Sdim      // Is the array too large?
1367212904Sdim      unsigned ActiveSizeBits
1368212904Sdim        = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1369212904Sdim      if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1370212904Sdim        Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1371212904Sdim          << ConstVal.toString(10)
1372212904Sdim          << ArraySize->getSourceRange();
1373198954Srdivacky    }
1374212904Sdim
1375198398Srdivacky    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1376193326Sed  }
1377193326Sed  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1378234353Sdim  if (!getLangOpts().C99) {
1379208600Srdivacky    if (T->isVariableArrayType()) {
1380208600Srdivacky      // Prohibit the use of non-POD types in VLAs.
1381224145Sdim      QualType BaseT = Context.getBaseElementType(T);
1382208600Srdivacky      if (!T->isDependentType() &&
1383224145Sdim          !BaseT.isPODType(Context) &&
1384224145Sdim          !BaseT->isObjCLifetimeType()) {
1385208600Srdivacky        Diag(Loc, diag::err_vla_non_pod)
1386224145Sdim          << BaseT;
1387208600Srdivacky        return QualType();
1388208600Srdivacky      }
1389208600Srdivacky      // Prohibit the use of VLAs during template argument deduction.
1390208600Srdivacky      else if (isSFINAEContext()) {
1391208600Srdivacky        Diag(Loc, diag::err_vla_in_sfinae);
1392208600Srdivacky        return QualType();
1393208600Srdivacky      }
1394208600Srdivacky      // Just extwarn about VLAs.
1395208600Srdivacky      else
1396208600Srdivacky        Diag(Loc, diag::ext_vla);
1397208600Srdivacky    } else if (ASM != ArrayType::Normal || Quals != 0)
1398234353Sdim      Diag(Loc,
1399234353Sdim           getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
1400234353Sdim                                     : diag::ext_c99_array_usage) << ASM;
1401193326Sed  }
1402193326Sed
1403193326Sed  return T;
1404193326Sed}
1405194613Sed
1406194613Sed/// \brief Build an ext-vector type.
1407194613Sed///
1408194613Sed/// Run the required checks for the extended vector type.
1409212904SdimQualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1410194613Sed                                  SourceLocation AttrLoc) {
1411194613Sed  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1412194613Sed  // in conjunction with complex types (pointers, arrays, functions, etc.).
1413198092Srdivacky  if (!T->isDependentType() &&
1414194613Sed      !T->isIntegerType() && !T->isRealFloatingType()) {
1415194613Sed    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1416194613Sed    return QualType();
1417194613Sed  }
1418194613Sed
1419212904Sdim  if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1420194613Sed    llvm::APSInt vecSize(32);
1421212904Sdim    if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1422194613Sed      Diag(AttrLoc, diag::err_attribute_argument_not_int)
1423212904Sdim        << "ext_vector_type" << ArraySize->getSourceRange();
1424194613Sed      return QualType();
1425194613Sed    }
1426198092Srdivacky
1427198092Srdivacky    // unlike gcc's vector_size attribute, the size is specified as the
1428194613Sed    // number of elements, not the number of bytes.
1429198092Srdivacky    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1430198092Srdivacky
1431194613Sed    if (vectorSize == 0) {
1432194613Sed      Diag(AttrLoc, diag::err_attribute_zero_size)
1433212904Sdim      << ArraySize->getSourceRange();
1434194613Sed      return QualType();
1435194613Sed    }
1436198092Srdivacky
1437224145Sdim    return Context.getExtVectorType(T, vectorSize);
1438198092Srdivacky  }
1439198092Srdivacky
1440212904Sdim  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1441194613Sed}
1442198092Srdivacky
1443193326Sed/// \brief Build a function type.
1444193326Sed///
1445193326Sed/// This routine checks the function type according to C++ rules and
1446193326Sed/// under the assumption that the result type and parameter types have
1447193326Sed/// just been instantiated from a template. It therefore duplicates
1448193326Sed/// some of the behavior of GetTypeForDeclarator, but in a much
1449193326Sed/// simpler form that is only suitable for this narrow use case.
1450193326Sed///
1451193326Sed/// \param T The return type of the function.
1452193326Sed///
1453193326Sed/// \param ParamTypes The parameter types of the function. This array
1454193326Sed/// will be modified to account for adjustments to the types of the
1455193326Sed/// function parameters.
1456193326Sed///
1457193326Sed/// \param NumParamTypes The number of parameter types in ParamTypes.
1458193326Sed///
1459193326Sed/// \param Variadic Whether this is a variadic function type.
1460193326Sed///
1461234353Sdim/// \param HasTrailingReturn Whether this function has a trailing return type.
1462234353Sdim///
1463193326Sed/// \param Quals The cvr-qualifiers to be applied to the function type.
1464193326Sed///
1465193326Sed/// \param Loc The location of the entity whose type involves this
1466193326Sed/// function type or, if there is no such entity, the location of the
1467193326Sed/// type that will have function type.
1468193326Sed///
1469193326Sed/// \param Entity The name of the entity that involves the function
1470193326Sed/// type, if known.
1471193326Sed///
1472193326Sed/// \returns A suitable function type, if there are no
1473193326Sed/// errors. Otherwise, returns a NULL type.
1474193326SedQualType Sema::BuildFunctionType(QualType T,
1475198092Srdivacky                                 QualType *ParamTypes,
1476193326Sed                                 unsigned NumParamTypes,
1477234353Sdim                                 bool Variadic, bool HasTrailingReturn,
1478234353Sdim                                 unsigned Quals,
1479218893Sdim                                 RefQualifierKind RefQualifier,
1480212904Sdim                                 SourceLocation Loc, DeclarationName Entity,
1481218893Sdim                                 FunctionType::ExtInfo Info) {
1482193326Sed  if (T->isArrayType() || T->isFunctionType()) {
1483202379Srdivacky    Diag(Loc, diag::err_func_returning_array_function)
1484202379Srdivacky      << T->isFunctionType() << T;
1485193326Sed    return QualType();
1486193326Sed  }
1487226633Sdim
1488226633Sdim  // Functions cannot return half FP.
1489226633Sdim  if (T->isHalfType()) {
1490226633Sdim    Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1491226633Sdim      FixItHint::CreateInsertion(Loc, "*");
1492226633Sdim    return QualType();
1493226633Sdim  }
1494226633Sdim
1495193326Sed  bool Invalid = false;
1496193326Sed  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
1497226633Sdim    // FIXME: Loc is too inprecise here, should use proper locations for args.
1498224145Sdim    QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1499193326Sed    if (ParamType->isVoidType()) {
1500193326Sed      Diag(Loc, diag::err_param_with_void_type);
1501193326Sed      Invalid = true;
1502226633Sdim    } else if (ParamType->isHalfType()) {
1503226633Sdim      // Disallow half FP arguments.
1504226633Sdim      Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1505226633Sdim        FixItHint::CreateInsertion(Loc, "*");
1506226633Sdim      Invalid = true;
1507193326Sed    }
1508193326Sed
1509198398Srdivacky    ParamTypes[Idx] = ParamType;
1510193326Sed  }
1511193326Sed
1512193326Sed  if (Invalid)
1513193326Sed    return QualType();
1514193326Sed
1515218893Sdim  FunctionProtoType::ExtProtoInfo EPI;
1516218893Sdim  EPI.Variadic = Variadic;
1517234353Sdim  EPI.HasTrailingReturn = HasTrailingReturn;
1518218893Sdim  EPI.TypeQuals = Quals;
1519218893Sdim  EPI.RefQualifier = RefQualifier;
1520218893Sdim  EPI.ExtInfo = Info;
1521218893Sdim
1522218893Sdim  return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
1523193326Sed}
1524198092Srdivacky
1525194179Sed/// \brief Build a member pointer type \c T Class::*.
1526194179Sed///
1527194179Sed/// \param T the type to which the member pointer refers.
1528194179Sed/// \param Class the class type into which the member pointer points.
1529194179Sed/// \param Loc the location where this type begins
1530194179Sed/// \param Entity the name of the entity that will have this member pointer type
1531194179Sed///
1532194179Sed/// \returns a member pointer type, if successful, or a NULL type if there was
1533194179Sed/// an error.
1534198092SrdivackyQualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1535210299Sed                                      SourceLocation Loc,
1536194179Sed                                      DeclarationName Entity) {
1537194179Sed  // Verify that we're not building a pointer to pointer to function with
1538194179Sed  // exception specification.
1539194179Sed  if (CheckDistantExceptionSpec(T)) {
1540194179Sed    Diag(Loc, diag::err_distant_exception_spec);
1541194179Sed
1542194179Sed    // FIXME: If we're doing this as part of template instantiation,
1543194179Sed    // we should return immediately.
1544194179Sed
1545194179Sed    // Build the type anyway, but use the canonical type so that the
1546194179Sed    // exception specifiers are stripped off.
1547194179Sed    T = Context.getCanonicalType(T);
1548194179Sed  }
1549194179Sed
1550210299Sed  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1551194179Sed  //   with reference type, or "cv void."
1552194179Sed  if (T->isReferenceType()) {
1553195341Sed    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1554198893Srdivacky      << (Entity? Entity.getAsString() : "type name") << T;
1555194179Sed    return QualType();
1556194179Sed  }
1557194179Sed
1558194179Sed  if (T->isVoidType()) {
1559194179Sed    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1560194179Sed      << (Entity? Entity.getAsString() : "type name");
1561194179Sed    return QualType();
1562194179Sed  }
1563194179Sed
1564194179Sed  if (!Class->isDependentType() && !Class->isRecordType()) {
1565194179Sed    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1566194179Sed    return QualType();
1567194179Sed  }
1568194179Sed
1569212904Sdim  // In the Microsoft ABI, the class is allowed to be an incomplete
1570212904Sdim  // type. In such cases, the compiler makes a worst-case assumption.
1571212904Sdim  // We make no such assumption right now, so emit an error if the
1572212904Sdim  // class isn't a complete type.
1573226633Sdim  if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
1574212904Sdim      RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1575212904Sdim    return QualType();
1576212904Sdim
1577210299Sed  return Context.getMemberPointerType(T, Class.getTypePtr());
1578194179Sed}
1579198092Srdivacky
1580194179Sed/// \brief Build a block pointer type.
1581194179Sed///
1582194179Sed/// \param T The type to which we'll be building a block pointer.
1583194179Sed///
1584198092Srdivacky/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
1585194179Sed///
1586194179Sed/// \param Loc The location of the entity whose type involves this
1587194179Sed/// block pointer type or, if there is no such entity, the location of the
1588194179Sed/// type that will have block pointer type.
1589194179Sed///
1590194179Sed/// \param Entity The name of the entity that involves the block pointer
1591194179Sed/// type, if known.
1592194179Sed///
1593194179Sed/// \returns A suitable block pointer type, if there are no
1594194179Sed/// errors. Otherwise, returns a NULL type.
1595210299SedQualType Sema::BuildBlockPointerType(QualType T,
1596198092Srdivacky                                     SourceLocation Loc,
1597194179Sed                                     DeclarationName Entity) {
1598198092Srdivacky  if (!T->isFunctionType()) {
1599194179Sed    Diag(Loc, diag::err_nonfunction_block_type);
1600194179Sed    return QualType();
1601194179Sed  }
1602198092Srdivacky
1603210299Sed  return Context.getBlockPointerType(T);
1604194179Sed}
1605194179Sed
1606212904SdimQualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1607212904Sdim  QualType QT = Ty.get();
1608198893Srdivacky  if (QT.isNull()) {
1609200583Srdivacky    if (TInfo) *TInfo = 0;
1610198893Srdivacky    return QualType();
1611198893Srdivacky  }
1612198893Srdivacky
1613200583Srdivacky  TypeSourceInfo *DI = 0;
1614218893Sdim  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1615198092Srdivacky    QT = LIT->getType();
1616200583Srdivacky    DI = LIT->getTypeSourceInfo();
1617198092Srdivacky  }
1618198092Srdivacky
1619200583Srdivacky  if (TInfo) *TInfo = DI;
1620198092Srdivacky  return QT;
1621198092Srdivacky}
1622198092Srdivacky
1623224145Sdimstatic void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1624224145Sdim                                            Qualifiers::ObjCLifetime ownership,
1625224145Sdim                                            unsigned chunkIndex);
1626224145Sdim
1627224145Sdim/// Given that this is the declaration of a parameter under ARC,
1628224145Sdim/// attempt to infer attributes and such for pointer-to-whatever
1629224145Sdim/// types.
1630224145Sdimstatic void inferARCWriteback(TypeProcessingState &state,
1631224145Sdim                              QualType &declSpecType) {
1632224145Sdim  Sema &S = state.getSema();
1633224145Sdim  Declarator &declarator = state.getDeclarator();
1634224145Sdim
1635224145Sdim  // TODO: should we care about decl qualifiers?
1636224145Sdim
1637224145Sdim  // Check whether the declarator has the expected form.  We walk
1638224145Sdim  // from the inside out in order to make the block logic work.
1639224145Sdim  unsigned outermostPointerIndex = 0;
1640224145Sdim  bool isBlockPointer = false;
1641224145Sdim  unsigned numPointers = 0;
1642224145Sdim  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1643224145Sdim    unsigned chunkIndex = i;
1644224145Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1645224145Sdim    switch (chunk.Kind) {
1646224145Sdim    case DeclaratorChunk::Paren:
1647224145Sdim      // Ignore parens.
1648224145Sdim      break;
1649224145Sdim
1650224145Sdim    case DeclaratorChunk::Reference:
1651224145Sdim    case DeclaratorChunk::Pointer:
1652224145Sdim      // Count the number of pointers.  Treat references
1653224145Sdim      // interchangeably as pointers; if they're mis-ordered, normal
1654224145Sdim      // type building will discover that.
1655224145Sdim      outermostPointerIndex = chunkIndex;
1656224145Sdim      numPointers++;
1657224145Sdim      break;
1658224145Sdim
1659224145Sdim    case DeclaratorChunk::BlockPointer:
1660224145Sdim      // If we have a pointer to block pointer, that's an acceptable
1661224145Sdim      // indirect reference; anything else is not an application of
1662224145Sdim      // the rules.
1663224145Sdim      if (numPointers != 1) return;
1664224145Sdim      numPointers++;
1665224145Sdim      outermostPointerIndex = chunkIndex;
1666224145Sdim      isBlockPointer = true;
1667224145Sdim
1668224145Sdim      // We don't care about pointer structure in return values here.
1669224145Sdim      goto done;
1670224145Sdim
1671224145Sdim    case DeclaratorChunk::Array: // suppress if written (id[])?
1672224145Sdim    case DeclaratorChunk::Function:
1673224145Sdim    case DeclaratorChunk::MemberPointer:
1674224145Sdim      return;
1675224145Sdim    }
1676224145Sdim  }
1677224145Sdim done:
1678224145Sdim
1679224145Sdim  // If we have *one* pointer, then we want to throw the qualifier on
1680224145Sdim  // the declaration-specifiers, which means that it needs to be a
1681224145Sdim  // retainable object type.
1682224145Sdim  if (numPointers == 1) {
1683224145Sdim    // If it's not a retainable object type, the rule doesn't apply.
1684224145Sdim    if (!declSpecType->isObjCRetainableType()) return;
1685224145Sdim
1686224145Sdim    // If it already has lifetime, don't do anything.
1687224145Sdim    if (declSpecType.getObjCLifetime()) return;
1688224145Sdim
1689224145Sdim    // Otherwise, modify the type in-place.
1690224145Sdim    Qualifiers qs;
1691224145Sdim
1692224145Sdim    if (declSpecType->isObjCARCImplicitlyUnretainedType())
1693224145Sdim      qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1694224145Sdim    else
1695224145Sdim      qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1696224145Sdim    declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1697224145Sdim
1698224145Sdim  // If we have *two* pointers, then we want to throw the qualifier on
1699224145Sdim  // the outermost pointer.
1700224145Sdim  } else if (numPointers == 2) {
1701224145Sdim    // If we don't have a block pointer, we need to check whether the
1702224145Sdim    // declaration-specifiers gave us something that will turn into a
1703224145Sdim    // retainable object pointer after we slap the first pointer on it.
1704224145Sdim    if (!isBlockPointer && !declSpecType->isObjCObjectType())
1705224145Sdim      return;
1706224145Sdim
1707224145Sdim    // Look for an explicit lifetime attribute there.
1708224145Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1709224145Sdim    if (chunk.Kind != DeclaratorChunk::Pointer &&
1710224145Sdim        chunk.Kind != DeclaratorChunk::BlockPointer)
1711224145Sdim      return;
1712224145Sdim    for (const AttributeList *attr = chunk.getAttrs(); attr;
1713224145Sdim           attr = attr->getNext())
1714224145Sdim      if (attr->getKind() == AttributeList::AT_objc_ownership)
1715224145Sdim        return;
1716224145Sdim
1717224145Sdim    transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1718224145Sdim                                          outermostPointerIndex);
1719224145Sdim
1720224145Sdim  // Any other number of pointers/references does not trigger the rule.
1721224145Sdim  } else return;
1722224145Sdim
1723224145Sdim  // TODO: mark whether we did this inference?
1724224145Sdim}
1725224145Sdim
1726219077Sdimstatic void DiagnoseIgnoredQualifiers(unsigned Quals,
1727219077Sdim                                      SourceLocation ConstQualLoc,
1728219077Sdim                                      SourceLocation VolatileQualLoc,
1729219077Sdim                                      SourceLocation RestrictQualLoc,
1730219077Sdim                                      Sema& S) {
1731219077Sdim  std::string QualStr;
1732219077Sdim  unsigned NumQuals = 0;
1733219077Sdim  SourceLocation Loc;
1734219077Sdim
1735219077Sdim  FixItHint ConstFixIt;
1736219077Sdim  FixItHint VolatileFixIt;
1737219077Sdim  FixItHint RestrictFixIt;
1738219077Sdim
1739223017Sdim  const SourceManager &SM = S.getSourceManager();
1740223017Sdim
1741219077Sdim  // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1742219077Sdim  // find a range and grow it to encompass all the qualifiers, regardless of
1743219077Sdim  // the order in which they textually appear.
1744219077Sdim  if (Quals & Qualifiers::Const) {
1745219077Sdim    ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
1746223017Sdim    QualStr = "const";
1747219077Sdim    ++NumQuals;
1748223017Sdim    if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1749223017Sdim      Loc = ConstQualLoc;
1750219077Sdim  }
1751219077Sdim  if (Quals & Qualifiers::Volatile) {
1752219077Sdim    VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
1753223017Sdim    QualStr += (NumQuals == 0 ? "volatile" : " volatile");
1754223017Sdim    ++NumQuals;
1755223017Sdim    if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1756219077Sdim      Loc = VolatileQualLoc;
1757219077Sdim  }
1758219077Sdim  if (Quals & Qualifiers::Restrict) {
1759219077Sdim    RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
1760223017Sdim    QualStr += (NumQuals == 0 ? "restrict" : " restrict");
1761223017Sdim    ++NumQuals;
1762223017Sdim    if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1763219077Sdim      Loc = RestrictQualLoc;
1764219077Sdim  }
1765219077Sdim
1766219077Sdim  assert(NumQuals > 0 && "No known qualifiers?");
1767219077Sdim
1768219077Sdim  S.Diag(Loc, diag::warn_qual_return_type)
1769223017Sdim    << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
1770219077Sdim}
1771219077Sdim
1772224145Sdimstatic QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1773224145Sdim                                             TypeSourceInfo *&ReturnTypeInfo) {
1774224145Sdim  Sema &SemaRef = state.getSema();
1775224145Sdim  Declarator &D = state.getDeclarator();
1776193326Sed  QualType T;
1777224145Sdim  ReturnTypeInfo = 0;
1778203955Srdivacky
1779224145Sdim  // The TagDecl owned by the DeclSpec.
1780224145Sdim  TagDecl *OwnedTagDecl = 0;
1781218893Sdim
1782198893Srdivacky  switch (D.getName().getKind()) {
1783224145Sdim  case UnqualifiedId::IK_ImplicitSelfParam:
1784221345Sdim  case UnqualifiedId::IK_OperatorFunctionId:
1785198893Srdivacky  case UnqualifiedId::IK_Identifier:
1786199990Srdivacky  case UnqualifiedId::IK_LiteralOperatorId:
1787198893Srdivacky  case UnqualifiedId::IK_TemplateId:
1788224145Sdim    T = ConvertDeclSpecToType(state);
1789198893Srdivacky
1790203955Srdivacky    if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
1791224145Sdim      OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1792221345Sdim      // Owned declaration is embedded in declarator.
1793224145Sdim      OwnedTagDecl->setEmbeddedInDeclarator(true);
1794203955Srdivacky    }
1795193326Sed    break;
1796193326Sed
1797198893Srdivacky  case UnqualifiedId::IK_ConstructorName:
1798202379Srdivacky  case UnqualifiedId::IK_ConstructorTemplateId:
1799198893Srdivacky  case UnqualifiedId::IK_DestructorName:
1800193326Sed    // Constructors and destructors don't have return types. Use
1801202379Srdivacky    // "void" instead.
1802224145Sdim    T = SemaRef.Context.VoidTy;
1803193326Sed    break;
1804202379Srdivacky
1805202379Srdivacky  case UnqualifiedId::IK_ConversionFunctionId:
1806202379Srdivacky    // The result type of a conversion function is the type that it
1807202379Srdivacky    // converts to.
1808224145Sdim    T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
1809224145Sdim                                  &ReturnTypeInfo);
1810202379Srdivacky    break;
1811193326Sed  }
1812200583Srdivacky
1813218893Sdim  if (D.getAttributes())
1814218893Sdim    distributeTypeAttrsFromDeclarator(state, T);
1815218893Sdim
1816234353Sdim  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1817234353Sdim  // In C++11, a function declarator using 'auto' must have a trailing return
1818219077Sdim  // type (this is checked later) and we can skip this. In other languages
1819219077Sdim  // using auto, we need to check regardless.
1820218893Sdim  if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1821234353Sdim      (!SemaRef.getLangOpts().CPlusPlus0x || !D.isFunctionDeclarator())) {
1822195099Sed    int Error = -1;
1823198092Srdivacky
1824195099Sed    switch (D.getContext()) {
1825195099Sed    case Declarator::KNRTypeListContext:
1826226633Sdim      llvm_unreachable("K&R type lists aren't allowed in C++");
1827234353Sdim    case Declarator::LambdaExprContext:
1828234353Sdim      llvm_unreachable("Can't specify a type specifier in lambda grammar");
1829226633Sdim    case Declarator::ObjCParameterContext:
1830226633Sdim    case Declarator::ObjCResultContext:
1831195099Sed    case Declarator::PrototypeContext:
1832195099Sed      Error = 0; // Function prototype
1833195099Sed      break;
1834195099Sed    case Declarator::MemberContext:
1835223017Sdim      if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1836223017Sdim        break;
1837224145Sdim      switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
1838226633Sdim      case TTK_Enum: llvm_unreachable("unhandled tag kind");
1839208600Srdivacky      case TTK_Struct: Error = 1; /* Struct member */ break;
1840208600Srdivacky      case TTK_Union:  Error = 2; /* Union member */ break;
1841208600Srdivacky      case TTK_Class:  Error = 3; /* Class member */ break;
1842198092Srdivacky      }
1843195099Sed      break;
1844195099Sed    case Declarator::CXXCatchContext:
1845224145Sdim    case Declarator::ObjCCatchContext:
1846195099Sed      Error = 4; // Exception declaration
1847195099Sed      break;
1848195099Sed    case Declarator::TemplateParamContext:
1849195099Sed      Error = 5; // Template parameter
1850195099Sed      break;
1851195099Sed    case Declarator::BlockLiteralContext:
1852218893Sdim      Error = 6; // Block literal
1853195099Sed      break;
1854218893Sdim    case Declarator::TemplateTypeArgContext:
1855218893Sdim      Error = 7; // Template type argument
1856218893Sdim      break;
1857221345Sdim    case Declarator::AliasDeclContext:
1858223017Sdim    case Declarator::AliasTemplateContext:
1859221345Sdim      Error = 9; // Type alias
1860221345Sdim      break;
1861234353Sdim    case Declarator::TrailingReturnContext:
1862234353Sdim      Error = 10; // Function return type
1863234353Sdim      break;
1864218893Sdim    case Declarator::TypeNameContext:
1865224145Sdim      Error = 11; // Generic
1866218893Sdim      break;
1867195099Sed    case Declarator::FileContext:
1868195099Sed    case Declarator::BlockContext:
1869195099Sed    case Declarator::ForContext:
1870195099Sed    case Declarator::ConditionContext:
1871224145Sdim    case Declarator::CXXNewContext:
1872195099Sed      break;
1873195099Sed    }
1874195099Sed
1875219077Sdim    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1876219077Sdim      Error = 8;
1877219077Sdim
1878219077Sdim    // In Objective-C it is an error to use 'auto' on a function declarator.
1879219077Sdim    if (D.isFunctionDeclarator())
1880221345Sdim      Error = 10;
1881219077Sdim
1882234353Sdim    // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1883219077Sdim    // contains a trailing return type. That is only legal at the outermost
1884219077Sdim    // level. Check all declarator chunks (outermost first) anyway, to give
1885219077Sdim    // better diagnostics.
1886234353Sdim    if (SemaRef.getLangOpts().CPlusPlus0x && Error != -1) {
1887219077Sdim      for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1888219077Sdim        unsigned chunkIndex = e - i - 1;
1889219077Sdim        state.setCurrentChunkIndex(chunkIndex);
1890219077Sdim        DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1891219077Sdim        if (DeclType.Kind == DeclaratorChunk::Function) {
1892219077Sdim          const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1893219077Sdim          if (FTI.TrailingReturnType) {
1894219077Sdim            Error = -1;
1895219077Sdim            break;
1896219077Sdim          }
1897219077Sdim        }
1898219077Sdim      }
1899219077Sdim    }
1900219077Sdim
1901195099Sed    if (Error != -1) {
1902224145Sdim      SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1903224145Sdim                   diag::err_auto_not_allowed)
1904195099Sed        << Error;
1905224145Sdim      T = SemaRef.Context.IntTy;
1906195099Sed      D.setInvalidType(true);
1907234353Sdim    } else
1908234353Sdim      SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1909234353Sdim                   diag::warn_cxx98_compat_auto_type_specifier);
1910195099Sed  }
1911218893Sdim
1912234353Sdim  if (SemaRef.getLangOpts().CPlusPlus &&
1913226633Sdim      OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
1914224145Sdim    // Check the contexts where C++ forbids the declaration of a new class
1915224145Sdim    // or enumeration in a type-specifier-seq.
1916224145Sdim    switch (D.getContext()) {
1917234353Sdim    case Declarator::TrailingReturnContext:
1918234353Sdim      // Class and enumeration definitions are syntactically not allowed in
1919234353Sdim      // trailing return types.
1920234353Sdim      llvm_unreachable("parser should not have allowed this");
1921234353Sdim      break;
1922224145Sdim    case Declarator::FileContext:
1923224145Sdim    case Declarator::MemberContext:
1924224145Sdim    case Declarator::BlockContext:
1925224145Sdim    case Declarator::ForContext:
1926224145Sdim    case Declarator::BlockLiteralContext:
1927234353Sdim    case Declarator::LambdaExprContext:
1928234353Sdim      // C++11 [dcl.type]p3:
1929224145Sdim      //   A type-specifier-seq shall not define a class or enumeration unless
1930224145Sdim      //   it appears in the type-id of an alias-declaration (7.1.3) that is not
1931224145Sdim      //   the declaration of a template-declaration.
1932224145Sdim    case Declarator::AliasDeclContext:
1933224145Sdim      break;
1934224145Sdim    case Declarator::AliasTemplateContext:
1935224145Sdim      SemaRef.Diag(OwnedTagDecl->getLocation(),
1936224145Sdim             diag::err_type_defined_in_alias_template)
1937224145Sdim        << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1938224145Sdim      break;
1939224145Sdim    case Declarator::TypeNameContext:
1940224145Sdim    case Declarator::TemplateParamContext:
1941224145Sdim    case Declarator::CXXNewContext:
1942224145Sdim    case Declarator::CXXCatchContext:
1943224145Sdim    case Declarator::ObjCCatchContext:
1944224145Sdim    case Declarator::TemplateTypeArgContext:
1945224145Sdim      SemaRef.Diag(OwnedTagDecl->getLocation(),
1946224145Sdim             diag::err_type_defined_in_type_specifier)
1947224145Sdim        << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1948224145Sdim      break;
1949224145Sdim    case Declarator::PrototypeContext:
1950226633Sdim    case Declarator::ObjCParameterContext:
1951226633Sdim    case Declarator::ObjCResultContext:
1952224145Sdim    case Declarator::KNRTypeListContext:
1953224145Sdim      // C++ [dcl.fct]p6:
1954224145Sdim      //   Types shall not be defined in return or parameter types.
1955224145Sdim      SemaRef.Diag(OwnedTagDecl->getLocation(),
1956224145Sdim                   diag::err_type_defined_in_param_type)
1957224145Sdim        << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1958224145Sdim      break;
1959224145Sdim    case Declarator::ConditionContext:
1960224145Sdim      // C++ 6.4p2:
1961224145Sdim      // The type-specifier-seq shall not contain typedef and shall not declare
1962224145Sdim      // a new class or enumeration.
1963224145Sdim      SemaRef.Diag(OwnedTagDecl->getLocation(),
1964224145Sdim                   diag::err_type_defined_in_condition);
1965224145Sdim      break;
1966224145Sdim    }
1967224145Sdim  }
1968224145Sdim
1969224145Sdim  return T;
1970224145Sdim}
1971224145Sdim
1972234353Sdimstatic std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1973234353Sdim  std::string Quals =
1974234353Sdim    Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1975234353Sdim
1976234353Sdim  switch (FnTy->getRefQualifier()) {
1977234353Sdim  case RQ_None:
1978234353Sdim    break;
1979234353Sdim
1980234353Sdim  case RQ_LValue:
1981234353Sdim    if (!Quals.empty())
1982234353Sdim      Quals += ' ';
1983234353Sdim    Quals += '&';
1984234353Sdim    break;
1985234353Sdim
1986234353Sdim  case RQ_RValue:
1987234353Sdim    if (!Quals.empty())
1988234353Sdim      Quals += ' ';
1989234353Sdim    Quals += "&&";
1990234353Sdim    break;
1991234353Sdim  }
1992234353Sdim
1993234353Sdim  return Quals;
1994234353Sdim}
1995234353Sdim
1996234353Sdim/// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
1997234353Sdim/// can be contained within the declarator chunk DeclType, and produce an
1998234353Sdim/// appropriate diagnostic if not.
1999234353Sdimstatic void checkQualifiedFunction(Sema &S, QualType T,
2000234353Sdim                                   DeclaratorChunk &DeclType) {
2001234353Sdim  // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
2002234353Sdim  // cv-qualifier or a ref-qualifier can only appear at the topmost level
2003234353Sdim  // of a type.
2004234353Sdim  int DiagKind = -1;
2005234353Sdim  switch (DeclType.Kind) {
2006234353Sdim  case DeclaratorChunk::Paren:
2007234353Sdim  case DeclaratorChunk::MemberPointer:
2008234353Sdim    // These cases are permitted.
2009234353Sdim    return;
2010234353Sdim  case DeclaratorChunk::Array:
2011234353Sdim  case DeclaratorChunk::Function:
2012234353Sdim    // These cases don't allow function types at all; no need to diagnose the
2013234353Sdim    // qualifiers separately.
2014234353Sdim    return;
2015234353Sdim  case DeclaratorChunk::BlockPointer:
2016234353Sdim    DiagKind = 0;
2017234353Sdim    break;
2018234353Sdim  case DeclaratorChunk::Pointer:
2019234353Sdim    DiagKind = 1;
2020234353Sdim    break;
2021234353Sdim  case DeclaratorChunk::Reference:
2022234353Sdim    DiagKind = 2;
2023234353Sdim    break;
2024234353Sdim  }
2025234353Sdim
2026234353Sdim  assert(DiagKind != -1);
2027234353Sdim  S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
2028234353Sdim    << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
2029234353Sdim    << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
2030234353Sdim}
2031234353Sdim
2032224145Sdimstatic TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2033224145Sdim                                                QualType declSpecType,
2034224145Sdim                                                TypeSourceInfo *TInfo) {
2035224145Sdim
2036224145Sdim  QualType T = declSpecType;
2037224145Sdim  Declarator &D = state.getDeclarator();
2038224145Sdim  Sema &S = state.getSema();
2039224145Sdim  ASTContext &Context = S.Context;
2040234353Sdim  const LangOptions &LangOpts = S.getLangOpts();
2041224145Sdim
2042224145Sdim  bool ImplicitlyNoexcept = false;
2043224145Sdim  if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
2044224145Sdim      LangOpts.CPlusPlus0x) {
2045224145Sdim    OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
2046224145Sdim    /// In C++0x, deallocation functions (normal and array operator delete)
2047224145Sdim    /// are implicitly noexcept.
2048224145Sdim    if (OO == OO_Delete || OO == OO_Array_Delete)
2049224145Sdim      ImplicitlyNoexcept = true;
2050224145Sdim  }
2051224145Sdim
2052193326Sed  // The name we're declaring, if any.
2053193326Sed  DeclarationName Name;
2054193326Sed  if (D.getIdentifier())
2055193326Sed    Name = D.getIdentifier();
2056193326Sed
2057221345Sdim  // Does this declaration declare a typedef-name?
2058221345Sdim  bool IsTypedefName =
2059221345Sdim    D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2060223017Sdim    D.getContext() == Declarator::AliasDeclContext ||
2061223017Sdim    D.getContext() == Declarator::AliasTemplateContext;
2062221345Sdim
2063234353Sdim  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2064234353Sdim  bool IsQualifiedFunction = T->isFunctionProtoType() &&
2065234353Sdim      (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2066234353Sdim       T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2067234353Sdim
2068193326Sed  // Walk the DeclTypeInfo, building the recursive type as we go.
2069193326Sed  // DeclTypeInfos are ordered from the identifier out, which is
2070193326Sed  // opposite of what we want :).
2071198893Srdivacky  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2072218893Sdim    unsigned chunkIndex = e - i - 1;
2073218893Sdim    state.setCurrentChunkIndex(chunkIndex);
2074218893Sdim    DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2075234353Sdim    if (IsQualifiedFunction) {
2076234353Sdim      checkQualifiedFunction(S, T, DeclType);
2077234353Sdim      IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
2078234353Sdim    }
2079193326Sed    switch (DeclType.Kind) {
2080218893Sdim    case DeclaratorChunk::Paren:
2081224145Sdim      T = S.BuildParenType(T);
2082218893Sdim      break;
2083193326Sed    case DeclaratorChunk::BlockPointer:
2084193326Sed      // If blocks are disabled, emit an error.
2085193326Sed      if (!LangOpts.Blocks)
2086224145Sdim        S.Diag(DeclType.Loc, diag::err_blocks_disable);
2087198092Srdivacky
2088224145Sdim      T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
2089210299Sed      if (DeclType.Cls.TypeQuals)
2090224145Sdim        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
2091193326Sed      break;
2092193326Sed    case DeclaratorChunk::Pointer:
2093193326Sed      // Verify that we're not building a pointer to pointer to function with
2094193326Sed      // exception specification.
2095224145Sdim      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2096224145Sdim        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2097193326Sed        D.setInvalidType(true);
2098193326Sed        // Build the type anyway.
2099193326Sed      }
2100224145Sdim      if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
2101208600Srdivacky        T = Context.getObjCObjectPointerType(T);
2102210299Sed        if (DeclType.Ptr.TypeQuals)
2103224145Sdim          T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2104198092Srdivacky        break;
2105198092Srdivacky      }
2106224145Sdim      T = S.BuildPointerType(T, DeclType.Loc, Name);
2107210299Sed      if (DeclType.Ptr.TypeQuals)
2108224145Sdim        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2109218893Sdim
2110193326Sed      break;
2111198092Srdivacky    case DeclaratorChunk::Reference: {
2112193326Sed      // Verify that we're not building a reference to pointer to function with
2113193326Sed      // exception specification.
2114224145Sdim      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2115224145Sdim        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2116193326Sed        D.setInvalidType(true);
2117193326Sed        // Build the type anyway.
2118193326Sed      }
2119224145Sdim      T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
2120210299Sed
2121210299Sed      Qualifiers Quals;
2122210299Sed      if (DeclType.Ref.HasRestrict)
2123224145Sdim        T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
2124193326Sed      break;
2125198092Srdivacky    }
2126193326Sed    case DeclaratorChunk::Array: {
2127193326Sed      // Verify that we're not building an array of pointers to function with
2128193326Sed      // exception specification.
2129224145Sdim      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2130224145Sdim        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2131193326Sed        D.setInvalidType(true);
2132193326Sed        // Build the type anyway.
2133193326Sed      }
2134193326Sed      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
2135193326Sed      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
2136193326Sed      ArrayType::ArraySizeModifier ASM;
2137193326Sed      if (ATI.isStar)
2138193326Sed        ASM = ArrayType::Star;
2139193326Sed      else if (ATI.hasStatic)
2140193326Sed        ASM = ArrayType::Static;
2141193326Sed      else
2142193326Sed        ASM = ArrayType::Normal;
2143221345Sdim      if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
2144193326Sed        // FIXME: This check isn't quite right: it allows star in prototypes
2145193326Sed        // for function definitions, and disallows some edge cases detailed
2146193326Sed        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
2147224145Sdim        S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
2148193326Sed        ASM = ArrayType::Normal;
2149193326Sed        D.setInvalidType(true);
2150193326Sed      }
2151234353Sdim      T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
2152224145Sdim                           SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2153193326Sed      break;
2154193326Sed    }
2155193326Sed    case DeclaratorChunk::Function: {
2156193326Sed      // If the function declarator has a prototype (i.e. it is not () and
2157193326Sed      // does not have a K&R-style identifier list), then the arguments are part
2158193326Sed      // of the type, otherwise the argument list is ().
2159193326Sed      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2160234353Sdim      IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
2161193326Sed
2162218893Sdim      // Check for auto functions and trailing return type and adjust the
2163218893Sdim      // return type accordingly.
2164218893Sdim      if (!D.isInvalidType()) {
2165218893Sdim        // trailing-return-type is only required if we're declaring a function,
2166218893Sdim        // and not, for instance, a pointer to a function.
2167218893Sdim        if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2168218893Sdim            !FTI.TrailingReturnType && chunkIndex == 0) {
2169224145Sdim          S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2170218893Sdim               diag::err_auto_missing_trailing_return);
2171218893Sdim          T = Context.IntTy;
2172218893Sdim          D.setInvalidType(true);
2173218893Sdim        } else if (FTI.TrailingReturnType) {
2174219077Sdim          // T must be exactly 'auto' at this point. See CWG issue 681.
2175219077Sdim          if (isa<ParenType>(T)) {
2176224145Sdim            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2177219077Sdim                 diag::err_trailing_return_in_parens)
2178219077Sdim              << T << D.getDeclSpec().getSourceRange();
2179219077Sdim            D.setInvalidType(true);
2180234353Sdim          } else if (D.getContext() != Declarator::LambdaExprContext &&
2181234353Sdim                     (T.hasQualifiers() || !isa<AutoType>(T))) {
2182224145Sdim            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2183218893Sdim                 diag::err_trailing_return_without_auto)
2184218893Sdim              << T << D.getDeclSpec().getSourceRange();
2185218893Sdim            D.setInvalidType(true);
2186218893Sdim          }
2187218893Sdim
2188224145Sdim          T = S.GetTypeFromParser(
2189218893Sdim            ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
2190224145Sdim            &TInfo);
2191218893Sdim        }
2192218893Sdim      }
2193218893Sdim
2194219077Sdim      // C99 6.7.5.3p1: The return type may not be a function or array type.
2195219077Sdim      // For conversion functions, we'll diagnose this particular error later.
2196219077Sdim      if ((T->isArrayType() || T->isFunctionType()) &&
2197219077Sdim          (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2198219077Sdim        unsigned diagID = diag::err_func_returning_array_function;
2199219077Sdim        // Last processing chunk in block context means this function chunk
2200219077Sdim        // represents the block.
2201219077Sdim        if (chunkIndex == 0 &&
2202219077Sdim            D.getContext() == Declarator::BlockLiteralContext)
2203219077Sdim          diagID = diag::err_block_returning_array_function;
2204224145Sdim        S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2205219077Sdim        T = Context.IntTy;
2206219077Sdim        D.setInvalidType(true);
2207219077Sdim      }
2208219077Sdim
2209226633Sdim      // Do not allow returning half FP value.
2210226633Sdim      // FIXME: This really should be in BuildFunctionType.
2211226633Sdim      if (T->isHalfType()) {
2212226633Sdim        S.Diag(D.getIdentifierLoc(),
2213226633Sdim             diag::err_parameters_retval_cannot_have_fp16_type) << 1
2214226633Sdim          << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
2215226633Sdim        D.setInvalidType(true);
2216226633Sdim      }
2217226633Sdim
2218210299Sed      // cv-qualifiers on return types are pointless except when the type is a
2219210299Sed      // class type in C++.
2220221345Sdim      if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
2221221345Sdim          (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
2222224145Sdim          (!LangOpts.CPlusPlus || !T->isDependentType())) {
2223219077Sdim        assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2224219077Sdim        DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2225219077Sdim        assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2226219077Sdim
2227219077Sdim        DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2228219077Sdim
2229219077Sdim        DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2230219077Sdim            SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2231219077Sdim            SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2232219077Sdim            SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2233224145Sdim            S);
2234219077Sdim
2235219077Sdim      } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
2236224145Sdim          (!LangOpts.CPlusPlus ||
2237210299Sed           (!T->isDependentType() && !T->isRecordType()))) {
2238219077Sdim
2239219077Sdim        DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2240219077Sdim                                  D.getDeclSpec().getConstSpecLoc(),
2241219077Sdim                                  D.getDeclSpec().getVolatileSpecLoc(),
2242219077Sdim                                  D.getDeclSpec().getRestrictSpecLoc(),
2243224145Sdim                                  S);
2244210299Sed      }
2245219077Sdim
2246224145Sdim      if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
2247193326Sed        // C++ [dcl.fct]p6:
2248193326Sed        //   Types shall not be defined in return or parameter types.
2249212904Sdim        TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2250226633Sdim        if (Tag->isCompleteDefinition())
2251224145Sdim          S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2252193326Sed            << Context.getTypeDeclType(Tag);
2253193326Sed      }
2254193326Sed
2255193326Sed      // Exception specs are not allowed in typedefs. Complain, but add it
2256193326Sed      // anyway.
2257221345Sdim      if (IsTypedefName && FTI.getExceptionSpecType())
2258224145Sdim        S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2259223017Sdim          << (D.getContext() == Declarator::AliasDeclContext ||
2260223017Sdim              D.getContext() == Declarator::AliasTemplateContext);
2261193326Sed
2262224145Sdim      if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2263210299Sed        // Simple void foo(), where the incoming T is the result type.
2264210299Sed        T = Context.getFunctionNoProtoType(T);
2265210299Sed      } else {
2266210299Sed        // We allow a zero-parameter variadic function in C if the
2267210299Sed        // function is marked with the "overloadable" attribute. Scan
2268210299Sed        // for this attribute now.
2269224145Sdim        if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
2270193326Sed          bool Overloadable = false;
2271193326Sed          for (const AttributeList *Attrs = D.getAttributes();
2272193326Sed               Attrs; Attrs = Attrs->getNext()) {
2273193326Sed            if (Attrs->getKind() == AttributeList::AT_overloadable) {
2274193326Sed              Overloadable = true;
2275193326Sed              break;
2276193326Sed            }
2277193326Sed          }
2278193326Sed
2279193326Sed          if (!Overloadable)
2280224145Sdim            S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
2281193326Sed        }
2282210299Sed
2283210299Sed        if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
2284210299Sed          // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2285210299Sed          // definition.
2286224145Sdim          S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
2287210299Sed          D.setInvalidType(true);
2288210299Sed          break;
2289210299Sed        }
2290210299Sed
2291218893Sdim        FunctionProtoType::ExtProtoInfo EPI;
2292218893Sdim        EPI.Variadic = FTI.isVariadic;
2293234353Sdim        EPI.HasTrailingReturn = FTI.TrailingReturnType;
2294218893Sdim        EPI.TypeQuals = FTI.TypeQuals;
2295218893Sdim        EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2296218893Sdim                    : FTI.RefQualifierIsLValueRef? RQ_LValue
2297218893Sdim                    : RQ_RValue;
2298218893Sdim
2299193326Sed        // Otherwise, we have a function with an argument list that is
2300193326Sed        // potentially variadic.
2301226633Sdim        SmallVector<QualType, 16> ArgTys;
2302210299Sed        ArgTys.reserve(FTI.NumArgs);
2303198092Srdivacky
2304226633Sdim        SmallVector<bool, 16> ConsumedArguments;
2305224145Sdim        ConsumedArguments.reserve(FTI.NumArgs);
2306224145Sdim        bool HasAnyConsumedArguments = false;
2307224145Sdim
2308193326Sed        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2309212904Sdim          ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2310193326Sed          QualType ArgTy = Param->getType();
2311193326Sed          assert(!ArgTy.isNull() && "Couldn't parse type?");
2312193326Sed
2313193326Sed          // Adjust the parameter type.
2314224145Sdim          assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2315224145Sdim                 "Unadjusted type?");
2316193326Sed
2317193326Sed          // Look for 'void'.  void is allowed only as a single argument to a
2318193326Sed          // function with no other parameters (C99 6.7.5.3p10).  We record
2319193326Sed          // int(void) as a FunctionProtoType with an empty argument list.
2320193326Sed          if (ArgTy->isVoidType()) {
2321193326Sed            // If this is something like 'float(int, void)', reject it.  'void'
2322193326Sed            // is an incomplete type (C99 6.2.5p19) and function decls cannot
2323193326Sed            // have arguments of incomplete type.
2324193326Sed            if (FTI.NumArgs != 1 || FTI.isVariadic) {
2325224145Sdim              S.Diag(DeclType.Loc, diag::err_void_only_param);
2326193326Sed              ArgTy = Context.IntTy;
2327193326Sed              Param->setType(ArgTy);
2328193326Sed            } else if (FTI.ArgInfo[i].Ident) {
2329193326Sed              // Reject, but continue to parse 'int(void abc)'.
2330224145Sdim              S.Diag(FTI.ArgInfo[i].IdentLoc,
2331193326Sed                   diag::err_param_with_void_type);
2332193326Sed              ArgTy = Context.IntTy;
2333193326Sed              Param->setType(ArgTy);
2334193326Sed            } else {
2335193326Sed              // Reject, but continue to parse 'float(const void)'.
2336198092Srdivacky              if (ArgTy.hasQualifiers())
2337224145Sdim                S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2338198092Srdivacky
2339193326Sed              // Do not add 'void' to the ArgTys list.
2340193326Sed              break;
2341193326Sed            }
2342226633Sdim          } else if (ArgTy->isHalfType()) {
2343226633Sdim            // Disallow half FP arguments.
2344226633Sdim            // FIXME: This really should be in BuildFunctionType.
2345226633Sdim            S.Diag(Param->getLocation(),
2346226633Sdim               diag::err_parameters_retval_cannot_have_fp16_type) << 0
2347226633Sdim            << FixItHint::CreateInsertion(Param->getLocation(), "*");
2348226633Sdim            D.setInvalidType();
2349193326Sed          } else if (!FTI.hasPrototype) {
2350193326Sed            if (ArgTy->isPromotableIntegerType()) {
2351198092Srdivacky              ArgTy = Context.getPromotedIntegerType(ArgTy);
2352221345Sdim              Param->setKNRPromoted(true);
2353198092Srdivacky            } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
2354221345Sdim              if (BTy->getKind() == BuiltinType::Float) {
2355193326Sed                ArgTy = Context.DoubleTy;
2356221345Sdim                Param->setKNRPromoted(true);
2357221345Sdim              }
2358193326Sed            }
2359193326Sed          }
2360198092Srdivacky
2361224145Sdim          if (LangOpts.ObjCAutoRefCount) {
2362224145Sdim            bool Consumed = Param->hasAttr<NSConsumedAttr>();
2363224145Sdim            ConsumedArguments.push_back(Consumed);
2364224145Sdim            HasAnyConsumedArguments |= Consumed;
2365224145Sdim          }
2366224145Sdim
2367198398Srdivacky          ArgTys.push_back(ArgTy);
2368193326Sed        }
2369193326Sed
2370224145Sdim        if (HasAnyConsumedArguments)
2371224145Sdim          EPI.ConsumedArguments = ConsumedArguments.data();
2372224145Sdim
2373226633Sdim        SmallVector<QualType, 4> Exceptions;
2374234982Sdim        SmallVector<ParsedType, 2> DynamicExceptions;
2375234982Sdim        SmallVector<SourceRange, 2> DynamicExceptionRanges;
2376234982Sdim        Expr *NoexceptExpr = 0;
2377234982Sdim
2378221345Sdim        if (FTI.getExceptionSpecType() == EST_Dynamic) {
2379234982Sdim          // FIXME: It's rather inefficient to have to split into two vectors
2380234982Sdim          // here.
2381234982Sdim          unsigned N = FTI.NumExceptions;
2382234982Sdim          DynamicExceptions.reserve(N);
2383234982Sdim          DynamicExceptionRanges.reserve(N);
2384234982Sdim          for (unsigned I = 0; I != N; ++I) {
2385234982Sdim            DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
2386234982Sdim            DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
2387218893Sdim          }
2388221345Sdim        } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
2389234982Sdim          NoexceptExpr = FTI.NoexceptExpr;
2390234982Sdim        }
2391234982Sdim
2392234982Sdim        S.checkExceptionSpecification(FTI.getExceptionSpecType(),
2393234982Sdim                                      DynamicExceptions,
2394234982Sdim                                      DynamicExceptionRanges,
2395234982Sdim                                      NoexceptExpr,
2396234982Sdim                                      Exceptions,
2397234982Sdim                                      EPI);
2398234982Sdim
2399234982Sdim        if (FTI.getExceptionSpecType() == EST_None &&
2400234982Sdim            ImplicitlyNoexcept && chunkIndex == 0) {
2401221345Sdim          // Only the outermost chunk is marked noexcept, of course.
2402221345Sdim          EPI.ExceptionSpecType = EST_BasicNoexcept;
2403193326Sed        }
2404193326Sed
2405218893Sdim        T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
2406193326Sed      }
2407203955Srdivacky
2408193326Sed      break;
2409193326Sed    }
2410193326Sed    case DeclaratorChunk::MemberPointer:
2411193326Sed      // The scope spec must refer to a class, or be dependent.
2412212904Sdim      CXXScopeSpec &SS = DeclType.Mem.Scope();
2413193326Sed      QualType ClsType;
2414212904Sdim      if (SS.isInvalid()) {
2415207619Srdivacky        // Avoid emitting extra errors if we already errored on the scope.
2416207619Srdivacky        D.setInvalidType(true);
2417224145Sdim      } else if (S.isDependentScopeSpecifier(SS) ||
2418224145Sdim                 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
2419198092Srdivacky        NestedNameSpecifier *NNS
2420212904Sdim          = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2421198954Srdivacky        NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2422198954Srdivacky        switch (NNS->getKind()) {
2423198954Srdivacky        case NestedNameSpecifier::Identifier:
2424212904Sdim          ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
2425206084Srdivacky                                                 NNS->getAsIdentifier());
2426198954Srdivacky          break;
2427198954Srdivacky
2428198954Srdivacky        case NestedNameSpecifier::Namespace:
2429219077Sdim        case NestedNameSpecifier::NamespaceAlias:
2430198954Srdivacky        case NestedNameSpecifier::Global:
2431200583Srdivacky          llvm_unreachable("Nested-name-specifier must name a type");
2432212904Sdim
2433198954Srdivacky        case NestedNameSpecifier::TypeSpec:
2434198954Srdivacky        case NestedNameSpecifier::TypeSpecWithTemplate:
2435198954Srdivacky          ClsType = QualType(NNS->getAsType(), 0);
2436221345Sdim          // Note: if the NNS has a prefix and ClsType is a nondependent
2437221345Sdim          // TemplateSpecializationType, then the NNS prefix is NOT included
2438221345Sdim          // in ClsType; hence we wrap ClsType into an ElaboratedType.
2439221345Sdim          // NOTE: in particular, no wrap occurs if ClsType already is an
2440221345Sdim          // Elaborated, DependentName, or DependentTemplateSpecialization.
2441221345Sdim          if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
2442208600Srdivacky            ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
2443198954Srdivacky          break;
2444198954Srdivacky        }
2445193326Sed      } else {
2446224145Sdim        S.Diag(DeclType.Mem.Scope().getBeginLoc(),
2447194179Sed             diag::err_illegal_decl_mempointer_in_nonclass)
2448194179Sed          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2449194179Sed          << DeclType.Mem.Scope().getRange();
2450193326Sed        D.setInvalidType(true);
2451193326Sed      }
2452193326Sed
2453194179Sed      if (!ClsType.isNull())
2454224145Sdim        T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
2455194179Sed      if (T.isNull()) {
2456194179Sed        T = Context.IntTy;
2457193326Sed        D.setInvalidType(true);
2458210299Sed      } else if (DeclType.Mem.TypeQuals) {
2459224145Sdim        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
2460193326Sed      }
2461193326Sed      break;
2462193326Sed    }
2463193326Sed
2464193326Sed    if (T.isNull()) {
2465193326Sed      D.setInvalidType(true);
2466193326Sed      T = Context.IntTy;
2467193326Sed    }
2468193326Sed
2469193326Sed    // See if there are any attributes on this declarator chunk.
2470218893Sdim    if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2471218893Sdim      processTypeAttrs(state, T, false, attrs);
2472193326Sed  }
2473193326Sed
2474224145Sdim  if (LangOpts.CPlusPlus && T->isFunctionType()) {
2475198092Srdivacky    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
2476198893Srdivacky    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
2477193326Sed
2478218893Sdim    // C++ 8.3.5p4:
2479218893Sdim    //   A cv-qualifier-seq shall only be part of the function type
2480218893Sdim    //   for a nonstatic member function, the function type to which a pointer
2481218893Sdim    //   to member refers, or the top-level function type of a function typedef
2482218893Sdim    //   declaration.
2483218893Sdim    //
2484218893Sdim    // Core issue 547 also allows cv-qualifiers on function types that are
2485218893Sdim    // top-level template type arguments.
2486218893Sdim    bool FreeFunction;
2487218893Sdim    if (!D.getCXXScopeSpec().isSet()) {
2488234353Sdim      FreeFunction = ((D.getContext() != Declarator::MemberContext &&
2489234353Sdim                       D.getContext() != Declarator::LambdaExprContext) ||
2490218893Sdim                      D.getDeclSpec().isFriendSpecified());
2491218893Sdim    } else {
2492224145Sdim      DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
2493218893Sdim      FreeFunction = (DC && !DC->isRecord());
2494218893Sdim    }
2495218893Sdim
2496226633Sdim    // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
2497226633Sdim    // function that is not a constructor declares that function to be const.
2498226633Sdim    if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
2499234353Sdim        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static &&
2500226633Sdim        D.getName().getKind() != UnqualifiedId::IK_ConstructorName &&
2501226633Sdim        D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId &&
2502226633Sdim        !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
2503226633Sdim      // Rebuild function type adding a 'const' qualifier.
2504226633Sdim      FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2505226633Sdim      EPI.TypeQuals |= DeclSpec::TQ_const;
2506226633Sdim      T = Context.getFunctionType(FnTy->getResultType(),
2507226633Sdim                                  FnTy->arg_type_begin(),
2508226633Sdim                                  FnTy->getNumArgs(), EPI);
2509226633Sdim    }
2510226633Sdim
2511234353Sdim    // C++11 [dcl.fct]p6 (w/DR1417):
2512234353Sdim    // An attempt to specify a function type with a cv-qualifier-seq or a
2513234353Sdim    // ref-qualifier (including by typedef-name) is ill-formed unless it is:
2514234353Sdim    //  - the function type for a non-static member function,
2515234353Sdim    //  - the function type to which a pointer to member refers,
2516234353Sdim    //  - the top-level function type of a function typedef declaration or
2517234353Sdim    //    alias-declaration,
2518234353Sdim    //  - the type-id in the default argument of a type-parameter, or
2519234353Sdim    //  - the type-id of a template-argument for a type-parameter
2520234353Sdim    if (IsQualifiedFunction &&
2521234353Sdim        !(!FreeFunction &&
2522234353Sdim          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
2523234353Sdim        !IsTypedefName &&
2524234353Sdim        D.getContext() != Declarator::TemplateTypeArgContext) {
2525234353Sdim      SourceLocation Loc = D.getLocStart();
2526234353Sdim      SourceRange RemovalRange;
2527234353Sdim      unsigned I;
2528234353Sdim      if (D.isFunctionDeclarator(I)) {
2529234353Sdim        SmallVector<SourceLocation, 4> RemovalLocs;
2530234353Sdim        const DeclaratorChunk &Chunk = D.getTypeObject(I);
2531234353Sdim        assert(Chunk.Kind == DeclaratorChunk::Function);
2532234353Sdim        if (Chunk.Fun.hasRefQualifier())
2533234353Sdim          RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
2534234353Sdim        if (Chunk.Fun.TypeQuals & Qualifiers::Const)
2535234353Sdim          RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
2536234353Sdim        if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
2537234353Sdim          RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
2538234353Sdim        // FIXME: We do not track the location of the __restrict qualifier.
2539234353Sdim        //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
2540234353Sdim        //  RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
2541234353Sdim        if (!RemovalLocs.empty()) {
2542234353Sdim          std::sort(RemovalLocs.begin(), RemovalLocs.end(),
2543234353Sdim                    SourceManager::LocBeforeThanCompare(S.getSourceManager()));
2544234353Sdim          RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
2545234353Sdim          Loc = RemovalLocs.front();
2546218893Sdim        }
2547234353Sdim      }
2548193326Sed
2549234353Sdim      S.Diag(Loc, diag::err_invalid_qualified_function_type)
2550234353Sdim        << FreeFunction << D.isFunctionDeclarator() << T
2551234353Sdim        << getFunctionQualifiersAsString(FnTy)
2552234353Sdim        << FixItHint::CreateRemoval(RemovalRange);
2553234353Sdim
2554234353Sdim      // Strip the cv-qualifiers and ref-qualifiers from the type.
2555234353Sdim      FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2556234353Sdim      EPI.TypeQuals = 0;
2557234353Sdim      EPI.RefQualifier = RQ_None;
2558234353Sdim
2559234353Sdim      T = Context.getFunctionType(FnTy->getResultType(),
2560234353Sdim                                  FnTy->arg_type_begin(),
2561234353Sdim                                  FnTy->getNumArgs(), EPI);
2562193326Sed    }
2563193326Sed  }
2564198092Srdivacky
2565218893Sdim  // Apply any undistributed attributes from the declarator.
2566218893Sdim  if (!T.isNull())
2567218893Sdim    if (AttributeList *attrs = D.getAttributes())
2568218893Sdim      processTypeAttrs(state, T, false, attrs);
2569218893Sdim
2570218893Sdim  // Diagnose any ignored type attributes.
2571218893Sdim  if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2572218893Sdim
2573221345Sdim  // C++0x [dcl.constexpr]p9:
2574221345Sdim  //  A constexpr specifier used in an object declaration declares the object
2575221345Sdim  //  as const.
2576221345Sdim  if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
2577210299Sed    T.addConst();
2578210299Sed  }
2579210299Sed
2580218893Sdim  // If there was an ellipsis in the declarator, the declaration declares a
2581218893Sdim  // parameter pack whose type may be a pack expansion type.
2582218893Sdim  if (D.hasEllipsis() && !T.isNull()) {
2583218893Sdim    // C++0x [dcl.fct]p13:
2584218893Sdim    //   A declarator-id or abstract-declarator containing an ellipsis shall
2585218893Sdim    //   only be used in a parameter-declaration. Such a parameter-declaration
2586218893Sdim    //   is a parameter pack (14.5.3). [...]
2587218893Sdim    switch (D.getContext()) {
2588218893Sdim    case Declarator::PrototypeContext:
2589218893Sdim      // C++0x [dcl.fct]p13:
2590218893Sdim      //   [...] When it is part of a parameter-declaration-clause, the
2591218893Sdim      //   parameter pack is a function parameter pack (14.5.3). The type T
2592218893Sdim      //   of the declarator-id of the function parameter pack shall contain
2593218893Sdim      //   a template parameter pack; each template parameter pack in T is
2594218893Sdim      //   expanded by the function parameter pack.
2595218893Sdim      //
2596218893Sdim      // We represent function parameter packs as function parameters whose
2597218893Sdim      // type is a pack expansion.
2598218893Sdim      if (!T->containsUnexpandedParameterPack()) {
2599224145Sdim        S.Diag(D.getEllipsisLoc(),
2600218893Sdim             diag::err_function_parameter_pack_without_parameter_packs)
2601218893Sdim          << T <<  D.getSourceRange();
2602218893Sdim        D.setEllipsisLoc(SourceLocation());
2603218893Sdim      } else {
2604218893Sdim        T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2605218893Sdim      }
2606218893Sdim      break;
2607218893Sdim
2608218893Sdim    case Declarator::TemplateParamContext:
2609218893Sdim      // C++0x [temp.param]p15:
2610218893Sdim      //   If a template-parameter is a [...] is a parameter-declaration that
2611218893Sdim      //   declares a parameter pack (8.3.5), then the template-parameter is a
2612218893Sdim      //   template parameter pack (14.5.3).
2613218893Sdim      //
2614218893Sdim      // Note: core issue 778 clarifies that, if there are any unexpanded
2615218893Sdim      // parameter packs in the type of the non-type template parameter, then
2616218893Sdim      // it expands those parameter packs.
2617218893Sdim      if (T->containsUnexpandedParameterPack())
2618218893Sdim        T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2619226633Sdim      else
2620226633Sdim        S.Diag(D.getEllipsisLoc(),
2621226633Sdim               LangOpts.CPlusPlus0x
2622226633Sdim                 ? diag::warn_cxx98_compat_variadic_templates
2623226633Sdim                 : diag::ext_variadic_templates);
2624218893Sdim      break;
2625218893Sdim
2626218893Sdim    case Declarator::FileContext:
2627218893Sdim    case Declarator::KNRTypeListContext:
2628226633Sdim    case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
2629226633Sdim    case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
2630218893Sdim    case Declarator::TypeNameContext:
2631224145Sdim    case Declarator::CXXNewContext:
2632221345Sdim    case Declarator::AliasDeclContext:
2633223017Sdim    case Declarator::AliasTemplateContext:
2634218893Sdim    case Declarator::MemberContext:
2635218893Sdim    case Declarator::BlockContext:
2636218893Sdim    case Declarator::ForContext:
2637218893Sdim    case Declarator::ConditionContext:
2638218893Sdim    case Declarator::CXXCatchContext:
2639224145Sdim    case Declarator::ObjCCatchContext:
2640218893Sdim    case Declarator::BlockLiteralContext:
2641234353Sdim    case Declarator::LambdaExprContext:
2642234353Sdim    case Declarator::TrailingReturnContext:
2643218893Sdim    case Declarator::TemplateTypeArgContext:
2644218893Sdim      // FIXME: We may want to allow parameter packs in block-literal contexts
2645218893Sdim      // in the future.
2646224145Sdim      S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
2647218893Sdim      D.setEllipsisLoc(SourceLocation());
2648218893Sdim      break;
2649218893Sdim    }
2650218893Sdim  }
2651219077Sdim
2652210299Sed  if (T.isNull())
2653210299Sed    return Context.getNullTypeSourceInfo();
2654210299Sed  else if (D.isInvalidType())
2655210299Sed    return Context.getTrivialTypeSourceInfo(T);
2656224145Sdim
2657224145Sdim  return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2658193326Sed}
2659193326Sed
2660224145Sdim/// GetTypeForDeclarator - Convert the type for the specified
2661224145Sdim/// declarator to Type instances.
2662224145Sdim///
2663224145Sdim/// The result of this call will never be null, but the associated
2664224145Sdim/// type may be a null type if there's an unrecoverable error.
2665224145SdimTypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2666224145Sdim  // Determine the type of the declarator. Not all forms of declarator
2667224145Sdim  // have a type.
2668224145Sdim
2669224145Sdim  TypeProcessingState state(*this, D);
2670224145Sdim
2671224145Sdim  TypeSourceInfo *ReturnTypeInfo = 0;
2672224145Sdim  QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2673224145Sdim  if (T.isNull())
2674224145Sdim    return Context.getNullTypeSourceInfo();
2675224145Sdim
2676234353Sdim  if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
2677224145Sdim    inferARCWriteback(state, T);
2678224145Sdim
2679224145Sdim  return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
2680224145Sdim}
2681224145Sdim
2682224145Sdimstatic void transferARCOwnershipToDeclSpec(Sema &S,
2683224145Sdim                                           QualType &declSpecTy,
2684224145Sdim                                           Qualifiers::ObjCLifetime ownership) {
2685224145Sdim  if (declSpecTy->isObjCRetainableType() &&
2686224145Sdim      declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2687224145Sdim    Qualifiers qs;
2688224145Sdim    qs.addObjCLifetime(ownership);
2689224145Sdim    declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2690224145Sdim  }
2691224145Sdim}
2692224145Sdim
2693224145Sdimstatic void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2694224145Sdim                                            Qualifiers::ObjCLifetime ownership,
2695224145Sdim                                            unsigned chunkIndex) {
2696224145Sdim  Sema &S = state.getSema();
2697224145Sdim  Declarator &D = state.getDeclarator();
2698224145Sdim
2699224145Sdim  // Look for an explicit lifetime attribute.
2700224145Sdim  DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2701224145Sdim  for (const AttributeList *attr = chunk.getAttrs(); attr;
2702224145Sdim         attr = attr->getNext())
2703224145Sdim    if (attr->getKind() == AttributeList::AT_objc_ownership)
2704224145Sdim      return;
2705224145Sdim
2706224145Sdim  const char *attrStr = 0;
2707224145Sdim  switch (ownership) {
2708234353Sdim  case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
2709224145Sdim  case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2710224145Sdim  case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2711224145Sdim  case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2712224145Sdim  case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2713224145Sdim  }
2714224145Sdim
2715224145Sdim  // If there wasn't one, add one (with an invalid source location
2716224145Sdim  // so that we don't make an AttributedType for it).
2717224145Sdim  AttributeList *attr = D.getAttributePool()
2718224145Sdim    .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2719224145Sdim            /*scope*/ 0, SourceLocation(),
2720224145Sdim            &S.Context.Idents.get(attrStr), SourceLocation(),
2721224145Sdim            /*args*/ 0, 0,
2722224145Sdim            /*declspec*/ false, /*C++0x*/ false);
2723224145Sdim  spliceAttrIntoList(*attr, chunk.getAttrListRef());
2724224145Sdim
2725224145Sdim  // TODO: mark whether we did this inference?
2726224145Sdim}
2727224145Sdim
2728234353Sdim/// \brief Used for transfering ownership in casts resulting in l-values.
2729224145Sdimstatic void transferARCOwnership(TypeProcessingState &state,
2730224145Sdim                                 QualType &declSpecTy,
2731224145Sdim                                 Qualifiers::ObjCLifetime ownership) {
2732224145Sdim  Sema &S = state.getSema();
2733224145Sdim  Declarator &D = state.getDeclarator();
2734224145Sdim
2735224145Sdim  int inner = -1;
2736234353Sdim  bool hasIndirection = false;
2737224145Sdim  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2738224145Sdim    DeclaratorChunk &chunk = D.getTypeObject(i);
2739224145Sdim    switch (chunk.Kind) {
2740224145Sdim    case DeclaratorChunk::Paren:
2741224145Sdim      // Ignore parens.
2742224145Sdim      break;
2743224145Sdim
2744224145Sdim    case DeclaratorChunk::Array:
2745224145Sdim    case DeclaratorChunk::Reference:
2746224145Sdim    case DeclaratorChunk::Pointer:
2747234353Sdim      if (inner != -1)
2748234353Sdim        hasIndirection = true;
2749224145Sdim      inner = i;
2750224145Sdim      break;
2751224145Sdim
2752224145Sdim    case DeclaratorChunk::BlockPointer:
2753234353Sdim      if (inner != -1)
2754234353Sdim        transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2755234353Sdim      return;
2756224145Sdim
2757224145Sdim    case DeclaratorChunk::Function:
2758224145Sdim    case DeclaratorChunk::MemberPointer:
2759224145Sdim      return;
2760224145Sdim    }
2761224145Sdim  }
2762224145Sdim
2763224145Sdim  if (inner == -1)
2764234353Sdim    return;
2765224145Sdim
2766224145Sdim  DeclaratorChunk &chunk = D.getTypeObject(inner);
2767224145Sdim  if (chunk.Kind == DeclaratorChunk::Pointer) {
2768224145Sdim    if (declSpecTy->isObjCRetainableType())
2769224145Sdim      return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2770234353Sdim    if (declSpecTy->isObjCObjectType() && hasIndirection)
2771224145Sdim      return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2772224145Sdim  } else {
2773224145Sdim    assert(chunk.Kind == DeclaratorChunk::Array ||
2774224145Sdim           chunk.Kind == DeclaratorChunk::Reference);
2775224145Sdim    return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2776224145Sdim  }
2777224145Sdim}
2778224145Sdim
2779224145SdimTypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2780224145Sdim  TypeProcessingState state(*this, D);
2781224145Sdim
2782224145Sdim  TypeSourceInfo *ReturnTypeInfo = 0;
2783224145Sdim  QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2784224145Sdim  if (declSpecTy.isNull())
2785224145Sdim    return Context.getNullTypeSourceInfo();
2786224145Sdim
2787234353Sdim  if (getLangOpts().ObjCAutoRefCount) {
2788224145Sdim    Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
2789224145Sdim    if (ownership != Qualifiers::OCL_None)
2790224145Sdim      transferARCOwnership(state, declSpecTy, ownership);
2791224145Sdim  }
2792224145Sdim
2793224145Sdim  return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
2794224145Sdim}
2795224145Sdim
2796221345Sdim/// Map an AttributedType::Kind to an AttributeList::Kind.
2797221345Sdimstatic AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2798221345Sdim  switch (kind) {
2799221345Sdim  case AttributedType::attr_address_space:
2800221345Sdim    return AttributeList::AT_address_space;
2801221345Sdim  case AttributedType::attr_regparm:
2802221345Sdim    return AttributeList::AT_regparm;
2803221345Sdim  case AttributedType::attr_vector_size:
2804221345Sdim    return AttributeList::AT_vector_size;
2805221345Sdim  case AttributedType::attr_neon_vector_type:
2806221345Sdim    return AttributeList::AT_neon_vector_type;
2807221345Sdim  case AttributedType::attr_neon_polyvector_type:
2808221345Sdim    return AttributeList::AT_neon_polyvector_type;
2809221345Sdim  case AttributedType::attr_objc_gc:
2810221345Sdim    return AttributeList::AT_objc_gc;
2811224145Sdim  case AttributedType::attr_objc_ownership:
2812224145Sdim    return AttributeList::AT_objc_ownership;
2813221345Sdim  case AttributedType::attr_noreturn:
2814221345Sdim    return AttributeList::AT_noreturn;
2815221345Sdim  case AttributedType::attr_cdecl:
2816221345Sdim    return AttributeList::AT_cdecl;
2817221345Sdim  case AttributedType::attr_fastcall:
2818221345Sdim    return AttributeList::AT_fastcall;
2819221345Sdim  case AttributedType::attr_stdcall:
2820221345Sdim    return AttributeList::AT_stdcall;
2821221345Sdim  case AttributedType::attr_thiscall:
2822221345Sdim    return AttributeList::AT_thiscall;
2823221345Sdim  case AttributedType::attr_pascal:
2824221345Sdim    return AttributeList::AT_pascal;
2825221345Sdim  case AttributedType::attr_pcs:
2826221345Sdim    return AttributeList::AT_pcs;
2827221345Sdim  }
2828221345Sdim  llvm_unreachable("unexpected attribute kind!");
2829221345Sdim}
2830221345Sdim
2831221345Sdimstatic void fillAttributedTypeLoc(AttributedTypeLoc TL,
2832221345Sdim                                  const AttributeList *attrs) {
2833221345Sdim  AttributedType::Kind kind = TL.getAttrKind();
2834221345Sdim
2835221345Sdim  assert(attrs && "no type attributes in the expected location!");
2836221345Sdim  AttributeList::Kind parsedKind = getAttrListKind(kind);
2837221345Sdim  while (attrs->getKind() != parsedKind) {
2838221345Sdim    attrs = attrs->getNext();
2839221345Sdim    assert(attrs && "no matching attribute in expected location!");
2840221345Sdim  }
2841221345Sdim
2842221345Sdim  TL.setAttrNameLoc(attrs->getLoc());
2843221345Sdim  if (TL.hasAttrExprOperand())
2844221345Sdim    TL.setAttrExprOperand(attrs->getArg(0));
2845221345Sdim  else if (TL.hasAttrEnumOperand())
2846221345Sdim    TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2847221345Sdim
2848221345Sdim  // FIXME: preserve this information to here.
2849221345Sdim  if (TL.hasAttrOperand())
2850221345Sdim    TL.setAttrOperandParensRange(SourceRange());
2851221345Sdim}
2852221345Sdim
2853198398Srdivackynamespace {
2854198398Srdivacky  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
2855218893Sdim    ASTContext &Context;
2856198398Srdivacky    const DeclSpec &DS;
2857193326Sed
2858198398Srdivacky  public:
2859218893Sdim    TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2860218893Sdim      : Context(Context), DS(DS) {}
2861193326Sed
2862221345Sdim    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2863221345Sdim      fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2864221345Sdim      Visit(TL.getModifiedLoc());
2865221345Sdim    }
2866198398Srdivacky    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2867198398Srdivacky      Visit(TL.getUnqualifiedLoc());
2868198398Srdivacky    }
2869198398Srdivacky    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2870198398Srdivacky      TL.setNameLoc(DS.getTypeSpecTypeLoc());
2871198398Srdivacky    }
2872198398Srdivacky    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2873198398Srdivacky      TL.setNameLoc(DS.getTypeSpecTypeLoc());
2874208600Srdivacky    }
2875208600Srdivacky    void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2876208600Srdivacky      // Handle the base type, which might not have been written explicitly.
2877208600Srdivacky      if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2878208600Srdivacky        TL.setHasBaseTypeAsWritten(false);
2879218893Sdim        TL.getBaseLoc().initialize(Context, SourceLocation());
2880208600Srdivacky      } else {
2881208600Srdivacky        TL.setHasBaseTypeAsWritten(true);
2882208600Srdivacky        Visit(TL.getBaseLoc());
2883208600Srdivacky      }
2884193326Sed
2885208600Srdivacky      // Protocol qualifiers.
2886198398Srdivacky      if (DS.getProtocolQualifiers()) {
2887198398Srdivacky        assert(TL.getNumProtocols() > 0);
2888198398Srdivacky        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2889198398Srdivacky        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2890198398Srdivacky        TL.setRAngleLoc(DS.getSourceRange().getEnd());
2891198398Srdivacky        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2892198398Srdivacky          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2893198398Srdivacky      } else {
2894198398Srdivacky        assert(TL.getNumProtocols() == 0);
2895198398Srdivacky        TL.setLAngleLoc(SourceLocation());
2896198398Srdivacky        TL.setRAngleLoc(SourceLocation());
2897198398Srdivacky      }
2898198398Srdivacky    }
2899198398Srdivacky    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2900198398Srdivacky      TL.setStarLoc(SourceLocation());
2901208600Srdivacky      Visit(TL.getPointeeLoc());
2902198092Srdivacky    }
2903198893Srdivacky    void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
2904200583Srdivacky      TypeSourceInfo *TInfo = 0;
2905212904Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2906198893Srdivacky
2907198893Srdivacky      // If we got no declarator info from previous Sema routines,
2908198893Srdivacky      // just fill with the typespec loc.
2909200583Srdivacky      if (!TInfo) {
2910221345Sdim        TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
2911198893Srdivacky        return;
2912198893Srdivacky      }
2913198893Srdivacky
2914208600Srdivacky      TypeLoc OldTL = TInfo->getTypeLoc();
2915208600Srdivacky      if (TInfo->getType()->getAs<ElaboratedType>()) {
2916208600Srdivacky        ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2917208600Srdivacky        TemplateSpecializationTypeLoc NamedTL =
2918208600Srdivacky          cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2919208600Srdivacky        TL.copy(NamedTL);
2920208600Srdivacky      }
2921208600Srdivacky      else
2922208600Srdivacky        TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
2923198893Srdivacky    }
2924202379Srdivacky    void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2925202379Srdivacky      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2926202379Srdivacky      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2927202379Srdivacky      TL.setParensRange(DS.getTypeofParensRange());
2928202379Srdivacky    }
2929202379Srdivacky    void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2930202379Srdivacky      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2931202379Srdivacky      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2932202379Srdivacky      TL.setParensRange(DS.getTypeofParensRange());
2933212904Sdim      assert(DS.getRepAsType());
2934202379Srdivacky      TypeSourceInfo *TInfo = 0;
2935212904Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2936202379Srdivacky      TL.setUnderlyingTInfo(TInfo);
2937202379Srdivacky    }
2938223017Sdim    void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2939223017Sdim      // FIXME: This holds only because we only have one unary transform.
2940223017Sdim      assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2941223017Sdim      TL.setKWLoc(DS.getTypeSpecTypeLoc());
2942223017Sdim      TL.setParensRange(DS.getTypeofParensRange());
2943223017Sdim      assert(DS.getRepAsType());
2944223017Sdim      TypeSourceInfo *TInfo = 0;
2945223017Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2946223017Sdim      TL.setUnderlyingTInfo(TInfo);
2947223017Sdim    }
2948202879Srdivacky    void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2949202879Srdivacky      // By default, use the source location of the type specifier.
2950202879Srdivacky      TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2951202879Srdivacky      if (TL.needsExtraLocalData()) {
2952202879Srdivacky        // Set info for the written builtin specifiers.
2953202879Srdivacky        TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2954202879Srdivacky        // Try to have a meaningful source location.
2955202879Srdivacky        if (TL.getWrittenSignSpec() != TSS_unspecified)
2956202879Srdivacky          // Sign spec loc overrides the others (e.g., 'unsigned long').
2957202879Srdivacky          TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2958202879Srdivacky        else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2959202879Srdivacky          // Width spec loc overrides type spec loc (e.g., 'short int').
2960202879Srdivacky          TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2961202879Srdivacky      }
2962202879Srdivacky    }
2963208600Srdivacky    void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2964208600Srdivacky      ElaboratedTypeKeyword Keyword
2965208600Srdivacky        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2966218893Sdim      if (DS.getTypeSpecType() == TST_typename) {
2967208600Srdivacky        TypeSourceInfo *TInfo = 0;
2968212904Sdim        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2969208600Srdivacky        if (TInfo) {
2970208600Srdivacky          TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2971208600Srdivacky          return;
2972208600Srdivacky        }
2973208600Srdivacky      }
2974234353Sdim      TL.setElaboratedKeywordLoc(Keyword != ETK_None
2975234353Sdim                                 ? DS.getTypeSpecTypeLoc()
2976234353Sdim                                 : SourceLocation());
2977208600Srdivacky      const CXXScopeSpec& SS = DS.getTypeSpecScope();
2978221345Sdim      TL.setQualifierLoc(SS.getWithLocInContext(Context));
2979208600Srdivacky      Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2980208600Srdivacky    }
2981208600Srdivacky    void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2982234353Sdim      assert(DS.getTypeSpecType() == TST_typename);
2983234353Sdim      TypeSourceInfo *TInfo = 0;
2984234353Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2985234353Sdim      assert(TInfo);
2986234353Sdim      TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2987208600Srdivacky    }
2988210299Sed    void VisitDependentTemplateSpecializationTypeLoc(
2989210299Sed                                 DependentTemplateSpecializationTypeLoc TL) {
2990234353Sdim      assert(DS.getTypeSpecType() == TST_typename);
2991234353Sdim      TypeSourceInfo *TInfo = 0;
2992234353Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2993234353Sdim      assert(TInfo);
2994234353Sdim      TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2995234353Sdim                TInfo->getTypeLoc()));
2996210299Sed    }
2997221345Sdim    void VisitTagTypeLoc(TagTypeLoc TL) {
2998221345Sdim      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2999221345Sdim    }
3000226633Sdim    void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3001226633Sdim      TL.setKWLoc(DS.getTypeSpecTypeLoc());
3002226633Sdim      TL.setParensRange(DS.getTypeofParensRange());
3003226633Sdim
3004226633Sdim      TypeSourceInfo *TInfo = 0;
3005226633Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3006226633Sdim      TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
3007226633Sdim    }
3008208600Srdivacky
3009198398Srdivacky    void VisitTypeLoc(TypeLoc TL) {
3010198398Srdivacky      // FIXME: add other typespec types and change this to an assert.
3011218893Sdim      TL.initialize(Context, DS.getTypeSpecTypeLoc());
3012198092Srdivacky    }
3013198398Srdivacky  };
3014198398Srdivacky
3015198398Srdivacky  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
3016221345Sdim    ASTContext &Context;
3017198398Srdivacky    const DeclaratorChunk &Chunk;
3018198398Srdivacky
3019198398Srdivacky  public:
3020221345Sdim    DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3021221345Sdim      : Context(Context), Chunk(Chunk) {}
3022198398Srdivacky
3023198398Srdivacky    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3024200583Srdivacky      llvm_unreachable("qualified type locs not expected here!");
3025198092Srdivacky    }
3026198398Srdivacky
3027224145Sdim    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3028224145Sdim      fillAttributedTypeLoc(TL, Chunk.getAttrs());
3029224145Sdim    }
3030198398Srdivacky    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3031198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3032198398Srdivacky      TL.setCaretLoc(Chunk.Loc);
3033198092Srdivacky    }
3034198398Srdivacky    void VisitPointerTypeLoc(PointerTypeLoc TL) {
3035198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Pointer);
3036198398Srdivacky      TL.setStarLoc(Chunk.Loc);
3037198398Srdivacky    }
3038198398Srdivacky    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3039198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Pointer);
3040198398Srdivacky      TL.setStarLoc(Chunk.Loc);
3041198398Srdivacky    }
3042198398Srdivacky    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3043198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
3044221345Sdim      const CXXScopeSpec& SS = Chunk.Mem.Scope();
3045221345Sdim      NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3046221345Sdim
3047221345Sdim      const Type* ClsTy = TL.getClass();
3048221345Sdim      QualType ClsQT = QualType(ClsTy, 0);
3049221345Sdim      TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3050221345Sdim      // Now copy source location info into the type loc component.
3051221345Sdim      TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3052221345Sdim      switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3053221345Sdim      case NestedNameSpecifier::Identifier:
3054221345Sdim        assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3055221345Sdim        {
3056221345Sdim          DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
3057234353Sdim          DNTLoc.setElaboratedKeywordLoc(SourceLocation());
3058221345Sdim          DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3059221345Sdim          DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3060221345Sdim        }
3061221345Sdim        break;
3062221345Sdim
3063221345Sdim      case NestedNameSpecifier::TypeSpec:
3064221345Sdim      case NestedNameSpecifier::TypeSpecWithTemplate:
3065221345Sdim        if (isa<ElaboratedType>(ClsTy)) {
3066221345Sdim          ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
3067234353Sdim          ETLoc.setElaboratedKeywordLoc(SourceLocation());
3068221345Sdim          ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3069221345Sdim          TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3070221345Sdim          NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3071221345Sdim        } else {
3072221345Sdim          ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3073221345Sdim        }
3074221345Sdim        break;
3075221345Sdim
3076221345Sdim      case NestedNameSpecifier::Namespace:
3077221345Sdim      case NestedNameSpecifier::NamespaceAlias:
3078221345Sdim      case NestedNameSpecifier::Global:
3079221345Sdim        llvm_unreachable("Nested-name-specifier must name a type");
3080221345Sdim      }
3081221345Sdim
3082221345Sdim      // Finally fill in MemberPointerLocInfo fields.
3083198398Srdivacky      TL.setStarLoc(Chunk.Loc);
3084221345Sdim      TL.setClassTInfo(ClsTInfo);
3085198398Srdivacky    }
3086198398Srdivacky    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3087198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Reference);
3088198398Srdivacky      // 'Amp' is misleading: this might have been originally
3089198398Srdivacky      /// spelled with AmpAmp.
3090198398Srdivacky      TL.setAmpLoc(Chunk.Loc);
3091198398Srdivacky    }
3092198398Srdivacky    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3093198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Reference);
3094198398Srdivacky      assert(!Chunk.Ref.LValueRef);
3095198398Srdivacky      TL.setAmpAmpLoc(Chunk.Loc);
3096198398Srdivacky    }
3097198398Srdivacky    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3098198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Array);
3099198398Srdivacky      TL.setLBracketLoc(Chunk.Loc);
3100198398Srdivacky      TL.setRBracketLoc(Chunk.EndLoc);
3101198398Srdivacky      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3102198398Srdivacky    }
3103198398Srdivacky    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3104198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Function);
3105221345Sdim      TL.setLocalRangeBegin(Chunk.Loc);
3106221345Sdim      TL.setLocalRangeEnd(Chunk.EndLoc);
3107218893Sdim      TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
3108198398Srdivacky
3109198398Srdivacky      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3110198398Srdivacky      for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
3111212904Sdim        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
3112198398Srdivacky        TL.setArg(tpi++, Param);
3113198092Srdivacky      }
3114198398Srdivacky      // FIXME: exception specs
3115198092Srdivacky    }
3116218893Sdim    void VisitParenTypeLoc(ParenTypeLoc TL) {
3117218893Sdim      assert(Chunk.Kind == DeclaratorChunk::Paren);
3118218893Sdim      TL.setLParenLoc(Chunk.Loc);
3119218893Sdim      TL.setRParenLoc(Chunk.EndLoc);
3120218893Sdim    }
3121193326Sed
3122198398Srdivacky    void VisitTypeLoc(TypeLoc TL) {
3123200583Srdivacky      llvm_unreachable("unsupported TypeLoc kind in declarator!");
3124198092Srdivacky    }
3125198398Srdivacky  };
3126198398Srdivacky}
3127198092Srdivacky
3128200583Srdivacky/// \brief Create and instantiate a TypeSourceInfo with type source information.
3129198398Srdivacky///
3130198398Srdivacky/// \param T QualType referring to the type as written in source code.
3131207619Srdivacky///
3132207619Srdivacky/// \param ReturnTypeInfo For declarators whose return type does not show
3133207619Srdivacky/// up in the normal place in the declaration specifiers (such as a C++
3134207619Srdivacky/// conversion function), this pointer will refer to a type source information
3135207619Srdivacky/// for that return type.
3136200583SrdivackyTypeSourceInfo *
3137207619SrdivackySema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3138207619Srdivacky                                     TypeSourceInfo *ReturnTypeInfo) {
3139200583Srdivacky  TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3140200583Srdivacky  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3141198398Srdivacky
3142218893Sdim  // Handle parameter packs whose type is a pack expansion.
3143218893Sdim  if (isa<PackExpansionType>(T)) {
3144218893Sdim    cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
3145218893Sdim    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3146218893Sdim  }
3147218893Sdim
3148198893Srdivacky  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3149221345Sdim    while (isa<AttributedTypeLoc>(CurrTL)) {
3150221345Sdim      AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3151221345Sdim      fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3152221345Sdim      CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3153221345Sdim    }
3154221345Sdim
3155221345Sdim    DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3156198398Srdivacky    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3157195341Sed  }
3158198092Srdivacky
3159212904Sdim  // If we have different source information for the return type, use
3160212904Sdim  // that.  This really only applies to C++ conversion functions.
3161212904Sdim  if (ReturnTypeInfo) {
3162207619Srdivacky    TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3163207619Srdivacky    assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3164207619Srdivacky    memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3165212904Sdim  } else {
3166218893Sdim    TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3167207619Srdivacky  }
3168207619Srdivacky
3169200583Srdivacky  return TInfo;
3170198092Srdivacky}
3171195341Sed
3172200583Srdivacky/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
3173212904SdimParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3174198092Srdivacky  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3175198092Srdivacky  // and Sema during declaration parsing. Try deallocating/caching them when
3176198092Srdivacky  // it's appropriate, instead of allocating them and keeping them around.
3177218893Sdim  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3178218893Sdim                                                       TypeAlignment);
3179200583Srdivacky  new (LocT) LocInfoType(T, TInfo);
3180198092Srdivacky  assert(LocT->getTypeClass() != T->getTypeClass() &&
3181198092Srdivacky         "LocInfoType's TypeClass conflicts with an existing Type class");
3182212904Sdim  return ParsedType::make(QualType(LocT, 0));
3183198092Srdivacky}
3184195341Sed
3185198092Srdivackyvoid LocInfoType::getAsStringInternal(std::string &Str,
3186198092Srdivacky                                      const PrintingPolicy &Policy) const {
3187226633Sdim  llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3188198092Srdivacky         " was used directly instead of getting the QualType through"
3189198092Srdivacky         " GetTypeFromParser");
3190195341Sed}
3191195341Sed
3192212904SdimTypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3193193326Sed  // C99 6.7.6: Type names have no identifier.  This is already validated by
3194193326Sed  // the parser.
3195193326Sed  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
3196198092Srdivacky
3197224145Sdim  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3198210299Sed  QualType T = TInfo->getType();
3199193326Sed  if (D.isInvalidType())
3200193326Sed    return true;
3201193326Sed
3202226633Sdim  // Make sure there are no unused decl attributes on the declarator.
3203226633Sdim  // We don't want to do this for ObjC parameters because we're going
3204226633Sdim  // to apply them to the actual parameter declaration.
3205226633Sdim  if (D.getContext() != Declarator::ObjCParameterContext)
3206226633Sdim    checkUnusedDeclAttributes(D);
3207226633Sdim
3208234353Sdim  if (getLangOpts().CPlusPlus) {
3209193326Sed    // Check that there are no default arguments (C++ only).
3210193326Sed    CheckExtraCXXDefaultArguments(D);
3211193326Sed  }
3212193326Sed
3213212904Sdim  return CreateParsedType(T, TInfo);
3214193326Sed}
3215193326Sed
3216226633SdimParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3217226633Sdim  QualType T = Context.getObjCInstanceType();
3218226633Sdim  TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3219226633Sdim  return CreateParsedType(T, TInfo);
3220226633Sdim}
3221226633Sdim
3222226633Sdim
3223193326Sed//===----------------------------------------------------------------------===//
3224193326Sed// Type Attribute Processing
3225193326Sed//===----------------------------------------------------------------------===//
3226193326Sed
3227193326Sed/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3228193326Sed/// specified type.  The attribute contains 1 argument, the id of the address
3229193326Sed/// space for the type.
3230198092Srdivackystatic void HandleAddressSpaceTypeAttribute(QualType &Type,
3231193326Sed                                            const AttributeList &Attr, Sema &S){
3232198092Srdivacky
3233193326Sed  // If this type is already address space qualified, reject it.
3234226633Sdim  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3235226633Sdim  // qualifiers for two or more different address spaces."
3236193326Sed  if (Type.getAddressSpace()) {
3237193326Sed    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3238207619Srdivacky    Attr.setInvalid();
3239193326Sed    return;
3240193326Sed  }
3241198092Srdivacky
3242226633Sdim  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3243226633Sdim  // qualified by an address-space qualifier."
3244226633Sdim  if (Type->isFunctionType()) {
3245226633Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3246226633Sdim    Attr.setInvalid();
3247226633Sdim    return;
3248226633Sdim  }
3249226633Sdim
3250193326Sed  // Check the attribute arguments.
3251193326Sed  if (Attr.getNumArgs() != 1) {
3252193326Sed    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3253207619Srdivacky    Attr.setInvalid();
3254193326Sed    return;
3255193326Sed  }
3256193326Sed  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3257193326Sed  llvm::APSInt addrSpace(32);
3258208600Srdivacky  if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3259208600Srdivacky      !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3260193326Sed    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3261193326Sed      << ASArgExpr->getSourceRange();
3262207619Srdivacky    Attr.setInvalid();
3263193326Sed    return;
3264193326Sed  }
3265193326Sed
3266198092Srdivacky  // Bounds checking.
3267198092Srdivacky  if (addrSpace.isSigned()) {
3268198092Srdivacky    if (addrSpace.isNegative()) {
3269198092Srdivacky      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3270198092Srdivacky        << ASArgExpr->getSourceRange();
3271207619Srdivacky      Attr.setInvalid();
3272198092Srdivacky      return;
3273198092Srdivacky    }
3274198092Srdivacky    addrSpace.setIsSigned(false);
3275198092Srdivacky  }
3276198092Srdivacky  llvm::APSInt max(addrSpace.getBitWidth());
3277198092Srdivacky  max = Qualifiers::MaxAddressSpace;
3278198092Srdivacky  if (addrSpace > max) {
3279198092Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3280198092Srdivacky      << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
3281207619Srdivacky    Attr.setInvalid();
3282198092Srdivacky    return;
3283198092Srdivacky  }
3284198092Srdivacky
3285198092Srdivacky  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3286193326Sed  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3287193326Sed}
3288193326Sed
3289234353Sdim/// Does this type have a "direct" ownership qualifier?  That is,
3290234353Sdim/// is it written like "__strong id", as opposed to something like
3291234353Sdim/// "typeof(foo)", where that happens to be strong?
3292234353Sdimstatic bool hasDirectOwnershipQualifier(QualType type) {
3293234353Sdim  // Fast path: no qualifier at all.
3294234353Sdim  assert(type.getQualifiers().hasObjCLifetime());
3295234353Sdim
3296234353Sdim  while (true) {
3297234353Sdim    // __strong id
3298234353Sdim    if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3299234353Sdim      if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
3300234353Sdim        return true;
3301234353Sdim
3302234353Sdim      type = attr->getModifiedType();
3303234353Sdim
3304234353Sdim    // X *__strong (...)
3305234353Sdim    } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
3306234353Sdim      type = paren->getInnerType();
3307234353Sdim
3308234353Sdim    // That's it for things we want to complain about.  In particular,
3309234353Sdim    // we do not want to look through typedefs, typeof(expr),
3310234353Sdim    // typeof(type), or any other way that the type is somehow
3311234353Sdim    // abstracted.
3312234353Sdim    } else {
3313234353Sdim
3314234353Sdim      return false;
3315234353Sdim    }
3316234353Sdim  }
3317234353Sdim}
3318234353Sdim
3319224145Sdim/// handleObjCOwnershipTypeAttr - Process an objc_ownership
3320224145Sdim/// attribute on the specified type.
3321224145Sdim///
3322224145Sdim/// Returns 'true' if the attribute was handled.
3323224145Sdimstatic bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
3324224145Sdim                                       AttributeList &attr,
3325224145Sdim                                       QualType &type) {
3326234353Sdim  bool NonObjCPointer = false;
3327224145Sdim
3328234353Sdim  if (!type->isDependentType()) {
3329234353Sdim    if (const PointerType *ptr = type->getAs<PointerType>()) {
3330234353Sdim      QualType pointee = ptr->getPointeeType();
3331234353Sdim      if (pointee->isObjCRetainableType() || pointee->isPointerType())
3332234353Sdim        return false;
3333234353Sdim      // It is important not to lose the source info that there was an attribute
3334234353Sdim      // applied to non-objc pointer. We will create an attributed type but
3335234353Sdim      // its type will be the same as the original type.
3336234353Sdim      NonObjCPointer = true;
3337234353Sdim    } else if (!type->isObjCRetainableType()) {
3338234353Sdim      return false;
3339234353Sdim    }
3340234353Sdim  }
3341234353Sdim
3342224145Sdim  Sema &S = state.getSema();
3343226633Sdim  SourceLocation AttrLoc = attr.getLoc();
3344226633Sdim  if (AttrLoc.isMacroID())
3345226633Sdim    AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
3346224145Sdim
3347224145Sdim  if (!attr.getParameterName()) {
3348226633Sdim    S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
3349224145Sdim      << "objc_ownership" << 1;
3350224145Sdim    attr.setInvalid();
3351224145Sdim    return true;
3352224145Sdim  }
3353224145Sdim
3354234353Sdim  // Consume lifetime attributes without further comment outside of
3355234353Sdim  // ARC mode.
3356234353Sdim  if (!S.getLangOpts().ObjCAutoRefCount)
3357234353Sdim    return true;
3358234353Sdim
3359224145Sdim  Qualifiers::ObjCLifetime lifetime;
3360224145Sdim  if (attr.getParameterName()->isStr("none"))
3361224145Sdim    lifetime = Qualifiers::OCL_ExplicitNone;
3362224145Sdim  else if (attr.getParameterName()->isStr("strong"))
3363224145Sdim    lifetime = Qualifiers::OCL_Strong;
3364224145Sdim  else if (attr.getParameterName()->isStr("weak"))
3365224145Sdim    lifetime = Qualifiers::OCL_Weak;
3366224145Sdim  else if (attr.getParameterName()->isStr("autoreleasing"))
3367224145Sdim    lifetime = Qualifiers::OCL_Autoreleasing;
3368224145Sdim  else {
3369226633Sdim    S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
3370224145Sdim      << "objc_ownership" << attr.getParameterName();
3371224145Sdim    attr.setInvalid();
3372224145Sdim    return true;
3373224145Sdim  }
3374224145Sdim
3375234353Sdim  SplitQualType underlyingType = type.split();
3376224145Sdim
3377234353Sdim  // Check for redundant/conflicting ownership qualifiers.
3378234353Sdim  if (Qualifiers::ObjCLifetime previousLifetime
3379234353Sdim        = type.getQualifiers().getObjCLifetime()) {
3380234353Sdim    // If it's written directly, that's an error.
3381234353Sdim    if (hasDirectOwnershipQualifier(type)) {
3382234353Sdim      S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3383234353Sdim        << type;
3384234353Sdim      return true;
3385234353Sdim    }
3386234353Sdim
3387234353Sdim    // Otherwise, if the qualifiers actually conflict, pull sugar off
3388234353Sdim    // until we reach a type that is directly qualified.
3389234353Sdim    if (previousLifetime != lifetime) {
3390234353Sdim      // This should always terminate: the canonical type is
3391234353Sdim      // qualified, so some bit of sugar must be hiding it.
3392234353Sdim      while (!underlyingType.Quals.hasObjCLifetime()) {
3393234353Sdim        underlyingType = underlyingType.getSingleStepDesugaredType();
3394234353Sdim      }
3395234353Sdim      underlyingType.Quals.removeObjCLifetime();
3396234353Sdim    }
3397234353Sdim  }
3398234353Sdim
3399234353Sdim  underlyingType.Quals.addObjCLifetime(lifetime);
3400234353Sdim
3401234353Sdim  if (NonObjCPointer) {
3402234353Sdim    StringRef name = attr.getName()->getName();
3403234353Sdim    switch (lifetime) {
3404234353Sdim    case Qualifiers::OCL_None:
3405234353Sdim    case Qualifiers::OCL_ExplicitNone:
3406234353Sdim      break;
3407234353Sdim    case Qualifiers::OCL_Strong: name = "__strong"; break;
3408234353Sdim    case Qualifiers::OCL_Weak: name = "__weak"; break;
3409234353Sdim    case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
3410234353Sdim    }
3411234353Sdim    S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
3412234353Sdim      << name << type;
3413234353Sdim  }
3414234353Sdim
3415224145Sdim  QualType origType = type;
3416234353Sdim  if (!NonObjCPointer)
3417234353Sdim    type = S.Context.getQualifiedType(underlyingType);
3418224145Sdim
3419224145Sdim  // If we have a valid source location for the attribute, use an
3420224145Sdim  // AttributedType instead.
3421226633Sdim  if (AttrLoc.isValid())
3422224145Sdim    type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
3423224145Sdim                                       origType, type);
3424224145Sdim
3425224145Sdim  // Forbid __weak if the runtime doesn't support it.
3426224145Sdim  if (lifetime == Qualifiers::OCL_Weak &&
3427234353Sdim      !S.getLangOpts().ObjCRuntimeHasWeak && !NonObjCPointer) {
3428224145Sdim
3429224145Sdim    // Actually, delay this until we know what we're parsing.
3430224145Sdim    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3431224145Sdim      S.DelayedDiagnostics.add(
3432226633Sdim          sema::DelayedDiagnostic::makeForbiddenType(
3433226633Sdim              S.getSourceManager().getExpansionLoc(AttrLoc),
3434224145Sdim              diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3435224145Sdim    } else {
3436226633Sdim      S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
3437224145Sdim    }
3438224145Sdim
3439224145Sdim    attr.setInvalid();
3440224145Sdim    return true;
3441224145Sdim  }
3442224145Sdim
3443224145Sdim  // Forbid __weak for class objects marked as
3444224145Sdim  // objc_arc_weak_reference_unavailable
3445224145Sdim  if (lifetime == Qualifiers::OCL_Weak) {
3446224145Sdim    QualType T = type;
3447224145Sdim    while (const PointerType *ptr = T->getAs<PointerType>())
3448224145Sdim      T = ptr->getPointeeType();
3449224145Sdim    if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
3450224145Sdim      ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
3451224145Sdim      if (Class->isArcWeakrefUnavailable()) {
3452226633Sdim          S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
3453224145Sdim          S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3454224145Sdim                 diag::note_class_declared);
3455224145Sdim      }
3456224145Sdim    }
3457224145Sdim  }
3458224145Sdim
3459224145Sdim  return true;
3460224145Sdim}
3461224145Sdim
3462218893Sdim/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3463218893Sdim/// attribute on the specified type.  Returns true to indicate that
3464218893Sdim/// the attribute was handled, false to indicate that the type does
3465218893Sdim/// not permit the attribute.
3466218893Sdimstatic bool handleObjCGCTypeAttr(TypeProcessingState &state,
3467218893Sdim                                 AttributeList &attr,
3468218893Sdim                                 QualType &type) {
3469218893Sdim  Sema &S = state.getSema();
3470218893Sdim
3471218893Sdim  // Delay if this isn't some kind of pointer.
3472218893Sdim  if (!type->isPointerType() &&
3473218893Sdim      !type->isObjCObjectPointerType() &&
3474218893Sdim      !type->isBlockPointerType())
3475218893Sdim    return false;
3476218893Sdim
3477218893Sdim  if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3478218893Sdim    S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3479218893Sdim    attr.setInvalid();
3480218893Sdim    return true;
3481193326Sed  }
3482198092Srdivacky
3483193326Sed  // Check the attribute arguments.
3484218893Sdim  if (!attr.getParameterName()) {
3485218893Sdim    S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
3486193326Sed      << "objc_gc" << 1;
3487218893Sdim    attr.setInvalid();
3488218893Sdim    return true;
3489193326Sed  }
3490198092Srdivacky  Qualifiers::GC GCAttr;
3491218893Sdim  if (attr.getNumArgs() != 0) {
3492218893Sdim    S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3493218893Sdim    attr.setInvalid();
3494218893Sdim    return true;
3495193326Sed  }
3496218893Sdim  if (attr.getParameterName()->isStr("weak"))
3497198092Srdivacky    GCAttr = Qualifiers::Weak;
3498218893Sdim  else if (attr.getParameterName()->isStr("strong"))
3499198092Srdivacky    GCAttr = Qualifiers::Strong;
3500193326Sed  else {
3501218893Sdim    S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3502218893Sdim      << "objc_gc" << attr.getParameterName();
3503218893Sdim    attr.setInvalid();
3504218893Sdim    return true;
3505193326Sed  }
3506198092Srdivacky
3507221345Sdim  QualType origType = type;
3508221345Sdim  type = S.Context.getObjCGCQualType(origType, GCAttr);
3509221345Sdim
3510221345Sdim  // Make an attributed type to preserve the source information.
3511221345Sdim  if (attr.getLoc().isValid())
3512221345Sdim    type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3513221345Sdim                                       origType, type);
3514221345Sdim
3515218893Sdim  return true;
3516193326Sed}
3517193326Sed
3518218893Sdimnamespace {
3519218893Sdim  /// A helper class to unwrap a type down to a function for the
3520218893Sdim  /// purposes of applying attributes there.
3521218893Sdim  ///
3522218893Sdim  /// Use:
3523218893Sdim  ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
3524218893Sdim  ///   if (unwrapped.isFunctionType()) {
3525218893Sdim  ///     const FunctionType *fn = unwrapped.get();
3526218893Sdim  ///     // change fn somehow
3527218893Sdim  ///     T = unwrapped.wrap(fn);
3528218893Sdim  ///   }
3529218893Sdim  struct FunctionTypeUnwrapper {
3530218893Sdim    enum WrapKind {
3531218893Sdim      Desugar,
3532218893Sdim      Parens,
3533218893Sdim      Pointer,
3534218893Sdim      BlockPointer,
3535218893Sdim      Reference,
3536218893Sdim      MemberPointer
3537218893Sdim    };
3538218893Sdim
3539218893Sdim    QualType Original;
3540218893Sdim    const FunctionType *Fn;
3541226633Sdim    SmallVector<unsigned char /*WrapKind*/, 8> Stack;
3542218893Sdim
3543218893Sdim    FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3544218893Sdim      while (true) {
3545218893Sdim        const Type *Ty = T.getTypePtr();
3546218893Sdim        if (isa<FunctionType>(Ty)) {
3547218893Sdim          Fn = cast<FunctionType>(Ty);
3548218893Sdim          return;
3549218893Sdim        } else if (isa<ParenType>(Ty)) {
3550218893Sdim          T = cast<ParenType>(Ty)->getInnerType();
3551218893Sdim          Stack.push_back(Parens);
3552218893Sdim        } else if (isa<PointerType>(Ty)) {
3553218893Sdim          T = cast<PointerType>(Ty)->getPointeeType();
3554218893Sdim          Stack.push_back(Pointer);
3555218893Sdim        } else if (isa<BlockPointerType>(Ty)) {
3556218893Sdim          T = cast<BlockPointerType>(Ty)->getPointeeType();
3557218893Sdim          Stack.push_back(BlockPointer);
3558218893Sdim        } else if (isa<MemberPointerType>(Ty)) {
3559218893Sdim          T = cast<MemberPointerType>(Ty)->getPointeeType();
3560218893Sdim          Stack.push_back(MemberPointer);
3561218893Sdim        } else if (isa<ReferenceType>(Ty)) {
3562218893Sdim          T = cast<ReferenceType>(Ty)->getPointeeType();
3563218893Sdim          Stack.push_back(Reference);
3564218893Sdim        } else {
3565218893Sdim          const Type *DTy = Ty->getUnqualifiedDesugaredType();
3566218893Sdim          if (Ty == DTy) {
3567218893Sdim            Fn = 0;
3568218893Sdim            return;
3569218893Sdim          }
3570218893Sdim
3571218893Sdim          T = QualType(DTy, 0);
3572218893Sdim          Stack.push_back(Desugar);
3573218893Sdim        }
3574218893Sdim      }
3575203955Srdivacky    }
3576198092Srdivacky
3577218893Sdim    bool isFunctionType() const { return (Fn != 0); }
3578218893Sdim    const FunctionType *get() const { return Fn; }
3579203955Srdivacky
3580218893Sdim    QualType wrap(Sema &S, const FunctionType *New) {
3581218893Sdim      // If T wasn't modified from the unwrapped type, do nothing.
3582218893Sdim      if (New == get()) return Original;
3583218893Sdim
3584218893Sdim      Fn = New;
3585218893Sdim      return wrap(S.Context, Original, 0);
3586206084Srdivacky    }
3587206084Srdivacky
3588218893Sdim  private:
3589218893Sdim    QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3590218893Sdim      if (I == Stack.size())
3591218893Sdim        return C.getQualifiedType(Fn, Old.getQualifiers());
3592218893Sdim
3593218893Sdim      // Build up the inner type, applying the qualifiers from the old
3594218893Sdim      // type to the new type.
3595218893Sdim      SplitQualType SplitOld = Old.split();
3596218893Sdim
3597218893Sdim      // As a special case, tail-recurse if there are no qualifiers.
3598234353Sdim      if (SplitOld.Quals.empty())
3599234353Sdim        return wrap(C, SplitOld.Ty, I);
3600234353Sdim      return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
3601218893Sdim    }
3602218893Sdim
3603218893Sdim    QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3604218893Sdim      if (I == Stack.size()) return QualType(Fn, 0);
3605218893Sdim
3606218893Sdim      switch (static_cast<WrapKind>(Stack[I++])) {
3607218893Sdim      case Desugar:
3608218893Sdim        // This is the point at which we potentially lose source
3609218893Sdim        // information.
3610218893Sdim        return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3611218893Sdim
3612218893Sdim      case Parens: {
3613218893Sdim        QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3614218893Sdim        return C.getParenType(New);
3615218893Sdim      }
3616218893Sdim
3617218893Sdim      case Pointer: {
3618218893Sdim        QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3619218893Sdim        return C.getPointerType(New);
3620218893Sdim      }
3621218893Sdim
3622218893Sdim      case BlockPointer: {
3623218893Sdim        QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3624218893Sdim        return C.getBlockPointerType(New);
3625218893Sdim      }
3626218893Sdim
3627218893Sdim      case MemberPointer: {
3628218893Sdim        const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3629218893Sdim        QualType New = wrap(C, OldMPT->getPointeeType(), I);
3630218893Sdim        return C.getMemberPointerType(New, OldMPT->getClass());
3631218893Sdim      }
3632218893Sdim
3633218893Sdim      case Reference: {
3634218893Sdim        const ReferenceType *OldRef = cast<ReferenceType>(Old);
3635218893Sdim        QualType New = wrap(C, OldRef->getPointeeType(), I);
3636218893Sdim        if (isa<LValueReferenceType>(OldRef))
3637218893Sdim          return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3638218893Sdim        else
3639218893Sdim          return C.getRValueReferenceType(New);
3640218893Sdim      }
3641218893Sdim      }
3642218893Sdim
3643218893Sdim      llvm_unreachable("unknown wrapping kind");
3644218893Sdim    }
3645218893Sdim  };
3646218893Sdim}
3647218893Sdim
3648218893Sdim/// Process an individual function attribute.  Returns true to
3649218893Sdim/// indicate that the attribute was handled, false if it wasn't.
3650218893Sdimstatic bool handleFunctionTypeAttr(TypeProcessingState &state,
3651218893Sdim                                   AttributeList &attr,
3652218893Sdim                                   QualType &type) {
3653218893Sdim  Sema &S = state.getSema();
3654218893Sdim
3655218893Sdim  FunctionTypeUnwrapper unwrapped(S, type);
3656218893Sdim
3657218893Sdim  if (attr.getKind() == AttributeList::AT_noreturn) {
3658218893Sdim    if (S.CheckNoReturnAttr(attr))
3659206084Srdivacky      return true;
3660206084Srdivacky
3661218893Sdim    // Delay if this is not a function type.
3662218893Sdim    if (!unwrapped.isFunctionType())
3663218893Sdim      return false;
3664218893Sdim
3665206084Srdivacky    // Otherwise we can process right away.
3666218893Sdim    FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3667218893Sdim    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3668218893Sdim    return true;
3669218893Sdim  }
3670206084Srdivacky
3671224145Sdim  // ns_returns_retained is not always a type attribute, but if we got
3672224145Sdim  // here, we're treating it as one right now.
3673224145Sdim  if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
3674234353Sdim    assert(S.getLangOpts().ObjCAutoRefCount &&
3675224145Sdim           "ns_returns_retained treated as type attribute in non-ARC");
3676224145Sdim    if (attr.getNumArgs()) return true;
3677224145Sdim
3678224145Sdim    // Delay if this is not a function type.
3679224145Sdim    if (!unwrapped.isFunctionType())
3680224145Sdim      return false;
3681224145Sdim
3682224145Sdim    FunctionType::ExtInfo EI
3683224145Sdim      = unwrapped.get()->getExtInfo().withProducesResult(true);
3684224145Sdim    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3685224145Sdim    return true;
3686224145Sdim  }
3687224145Sdim
3688218893Sdim  if (attr.getKind() == AttributeList::AT_regparm) {
3689218893Sdim    unsigned value;
3690218893Sdim    if (S.CheckRegparmAttr(attr, value))
3691218893Sdim      return true;
3692218893Sdim
3693218893Sdim    // Delay if this is not a function type.
3694218893Sdim    if (!unwrapped.isFunctionType())
3695206084Srdivacky      return false;
3696206084Srdivacky
3697218893Sdim    // Diagnose regparm with fastcall.
3698218893Sdim    const FunctionType *fn = unwrapped.get();
3699218893Sdim    CallingConv CC = fn->getCallConv();
3700218893Sdim    if (CC == CC_X86FastCall) {
3701218893Sdim      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3702218893Sdim        << FunctionType::getNameForCallConv(CC)
3703218893Sdim        << "regparm";
3704218893Sdim      attr.setInvalid();
3705218893Sdim      return true;
3706218893Sdim    }
3707218893Sdim
3708218893Sdim    FunctionType::ExtInfo EI =
3709218893Sdim      unwrapped.get()->getExtInfo().withRegParm(value);
3710218893Sdim    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3711218893Sdim    return true;
3712206084Srdivacky  }
3713206084Srdivacky
3714203955Srdivacky  // Otherwise, a calling convention.
3715218893Sdim  CallingConv CC;
3716218893Sdim  if (S.CheckCallingConvAttr(attr, CC))
3717218893Sdim    return true;
3718203955Srdivacky
3719203955Srdivacky  // Delay if the type didn't work out to a function.
3720218893Sdim  if (!unwrapped.isFunctionType()) return false;
3721203955Srdivacky
3722218893Sdim  const FunctionType *fn = unwrapped.get();
3723218893Sdim  CallingConv CCOld = fn->getCallConv();
3724204643Srdivacky  if (S.Context.getCanonicalCallConv(CC) ==
3725207619Srdivacky      S.Context.getCanonicalCallConv(CCOld)) {
3726218893Sdim    FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3727218893Sdim    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3728218893Sdim    return true;
3729207619Srdivacky  }
3730203955Srdivacky
3731226633Sdim  if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
3732203955Srdivacky    // Should we diagnose reapplications of the same convention?
3733218893Sdim    S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3734203955Srdivacky      << FunctionType::getNameForCallConv(CC)
3735203955Srdivacky      << FunctionType::getNameForCallConv(CCOld);
3736218893Sdim    attr.setInvalid();
3737218893Sdim    return true;
3738203955Srdivacky  }
3739203955Srdivacky
3740203955Srdivacky  // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3741203955Srdivacky  if (CC == CC_X86FastCall) {
3742218893Sdim    if (isa<FunctionNoProtoType>(fn)) {
3743218893Sdim      S.Diag(attr.getLoc(), diag::err_cconv_knr)
3744203955Srdivacky        << FunctionType::getNameForCallConv(CC);
3745218893Sdim      attr.setInvalid();
3746218893Sdim      return true;
3747203955Srdivacky    }
3748203955Srdivacky
3749218893Sdim    const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
3750203955Srdivacky    if (FnP->isVariadic()) {
3751218893Sdim      S.Diag(attr.getLoc(), diag::err_cconv_varargs)
3752203955Srdivacky        << FunctionType::getNameForCallConv(CC);
3753218893Sdim      attr.setInvalid();
3754218893Sdim      return true;
3755203955Srdivacky    }
3756218893Sdim
3757218893Sdim    // Also diagnose fastcall with regparm.
3758221345Sdim    if (fn->getHasRegParm()) {
3759218893Sdim      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3760218893Sdim        << "regparm"
3761218893Sdim        << FunctionType::getNameForCallConv(CC);
3762218893Sdim      attr.setInvalid();
3763218893Sdim      return true;
3764218893Sdim    }
3765203955Srdivacky  }
3766203955Srdivacky
3767218893Sdim  FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3768218893Sdim  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3769218893Sdim  return true;
3770198092Srdivacky}
3771198092Srdivacky
3772221345Sdim/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3773221345Sdimstatic void HandleOpenCLImageAccessAttribute(QualType& CurType,
3774221345Sdim                                             const AttributeList &Attr,
3775221345Sdim                                             Sema &S) {
3776221345Sdim  // Check the attribute arguments.
3777221345Sdim  if (Attr.getNumArgs() != 1) {
3778221345Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3779221345Sdim    Attr.setInvalid();
3780221345Sdim    return;
3781221345Sdim  }
3782221345Sdim  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3783221345Sdim  llvm::APSInt arg(32);
3784221345Sdim  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3785221345Sdim      !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3786221345Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3787221345Sdim      << "opencl_image_access" << sizeExpr->getSourceRange();
3788221345Sdim    Attr.setInvalid();
3789221345Sdim    return;
3790221345Sdim  }
3791221345Sdim  unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3792221345Sdim  switch (iarg) {
3793221345Sdim  case CLIA_read_only:
3794221345Sdim  case CLIA_write_only:
3795221345Sdim  case CLIA_read_write:
3796221345Sdim    // Implemented in a separate patch
3797221345Sdim    break;
3798221345Sdim  default:
3799221345Sdim    // Implemented in a separate patch
3800221345Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3801221345Sdim      << sizeExpr->getSourceRange();
3802221345Sdim    Attr.setInvalid();
3803221345Sdim    break;
3804221345Sdim  }
3805221345Sdim}
3806221345Sdim
3807200583Srdivacky/// HandleVectorSizeAttribute - this attribute is only applicable to integral
3808200583Srdivacky/// and float scalars, although arrays, pointers, and function return values are
3809200583Srdivacky/// allowed in conjunction with this construct. Aggregates with this attribute
3810200583Srdivacky/// are invalid, even if they are of the same size as a corresponding scalar.
3811200583Srdivacky/// The raw attribute should contain precisely 1 argument, the vector size for
3812200583Srdivacky/// the variable, measured in bytes. If curType and rawAttr are well formed,
3813200583Srdivacky/// this routine will return a new vector type.
3814210299Sedstatic void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3815210299Sed                                 Sema &S) {
3816218893Sdim  // Check the attribute arguments.
3817200583Srdivacky  if (Attr.getNumArgs() != 1) {
3818200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3819207619Srdivacky    Attr.setInvalid();
3820200583Srdivacky    return;
3821200583Srdivacky  }
3822200583Srdivacky  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3823200583Srdivacky  llvm::APSInt vecSize(32);
3824208600Srdivacky  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3825208600Srdivacky      !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
3826200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3827200583Srdivacky      << "vector_size" << sizeExpr->getSourceRange();
3828207619Srdivacky    Attr.setInvalid();
3829200583Srdivacky    return;
3830200583Srdivacky  }
3831200583Srdivacky  // the base type must be integer or float, and can't already be a vector.
3832212904Sdim  if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
3833200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
3834207619Srdivacky    Attr.setInvalid();
3835200583Srdivacky    return;
3836200583Srdivacky  }
3837200583Srdivacky  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3838200583Srdivacky  // vecSize is specified in bytes - convert to bits.
3839200583Srdivacky  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3840200583Srdivacky
3841200583Srdivacky  // the vector size needs to be an integral multiple of the type size.
3842200583Srdivacky  if (vectorSize % typeSize) {
3843200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3844200583Srdivacky      << sizeExpr->getSourceRange();
3845207619Srdivacky    Attr.setInvalid();
3846200583Srdivacky    return;
3847200583Srdivacky  }
3848200583Srdivacky  if (vectorSize == 0) {
3849200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3850200583Srdivacky      << sizeExpr->getSourceRange();
3851207619Srdivacky    Attr.setInvalid();
3852200583Srdivacky    return;
3853200583Srdivacky  }
3854200583Srdivacky
3855200583Srdivacky  // Success! Instantiate the vector type, the number of elements is > 0, and
3856200583Srdivacky  // not required to be a power of 2, unlike GCC.
3857210299Sed  CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
3858218893Sdim                                    VectorType::GenericVector);
3859200583Srdivacky}
3860200583Srdivacky
3861224145Sdim/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
3862224145Sdim/// a type.
3863224145Sdimstatic void HandleExtVectorTypeAttr(QualType &CurType,
3864224145Sdim                                    const AttributeList &Attr,
3865224145Sdim                                    Sema &S) {
3866224145Sdim  Expr *sizeExpr;
3867224145Sdim
3868224145Sdim  // Special case where the argument is a template id.
3869224145Sdim  if (Attr.getParameterName()) {
3870224145Sdim    CXXScopeSpec SS;
3871234353Sdim    SourceLocation TemplateKWLoc;
3872224145Sdim    UnqualifiedId id;
3873224145Sdim    id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
3874234353Sdim
3875234353Sdim    ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
3876234353Sdim                                          id, false, false);
3877224145Sdim    if (Size.isInvalid())
3878224145Sdim      return;
3879224145Sdim
3880224145Sdim    sizeExpr = Size.get();
3881224145Sdim  } else {
3882224145Sdim    // check the attribute arguments.
3883224145Sdim    if (Attr.getNumArgs() != 1) {
3884224145Sdim      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3885224145Sdim      return;
3886224145Sdim    }
3887224145Sdim    sizeExpr = Attr.getArg(0);
3888224145Sdim  }
3889224145Sdim
3890224145Sdim  // Create the vector type.
3891224145Sdim  QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
3892224145Sdim  if (!T.isNull())
3893224145Sdim    CurType = T;
3894224145Sdim}
3895224145Sdim
3896218893Sdim/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3897218893Sdim/// "neon_polyvector_type" attributes are used to create vector types that
3898218893Sdim/// are mangled according to ARM's ABI.  Otherwise, these types are identical
3899218893Sdim/// to those created with the "vector_size" attribute.  Unlike "vector_size"
3900218893Sdim/// the argument to these Neon attributes is the number of vector elements,
3901218893Sdim/// not the vector size in bytes.  The vector width and element type must
3902218893Sdim/// match one of the standard Neon vector types.
3903218893Sdimstatic void HandleNeonVectorTypeAttr(QualType& CurType,
3904218893Sdim                                     const AttributeList &Attr, Sema &S,
3905218893Sdim                                     VectorType::VectorKind VecKind,
3906218893Sdim                                     const char *AttrName) {
3907218893Sdim  // Check the attribute arguments.
3908218893Sdim  if (Attr.getNumArgs() != 1) {
3909218893Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3910218893Sdim    Attr.setInvalid();
3911218893Sdim    return;
3912218893Sdim  }
3913218893Sdim  // The number of elements must be an ICE.
3914218893Sdim  Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3915218893Sdim  llvm::APSInt numEltsInt(32);
3916218893Sdim  if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3917218893Sdim      !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3918218893Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3919218893Sdim      << AttrName << numEltsExpr->getSourceRange();
3920218893Sdim    Attr.setInvalid();
3921218893Sdim    return;
3922218893Sdim  }
3923218893Sdim  // Only certain element types are supported for Neon vectors.
3924218893Sdim  const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3925218893Sdim  if (!BTy ||
3926218893Sdim      (VecKind == VectorType::NeonPolyVector &&
3927218893Sdim       BTy->getKind() != BuiltinType::SChar &&
3928218893Sdim       BTy->getKind() != BuiltinType::Short) ||
3929218893Sdim      (BTy->getKind() != BuiltinType::SChar &&
3930218893Sdim       BTy->getKind() != BuiltinType::UChar &&
3931218893Sdim       BTy->getKind() != BuiltinType::Short &&
3932218893Sdim       BTy->getKind() != BuiltinType::UShort &&
3933218893Sdim       BTy->getKind() != BuiltinType::Int &&
3934218893Sdim       BTy->getKind() != BuiltinType::UInt &&
3935218893Sdim       BTy->getKind() != BuiltinType::LongLong &&
3936218893Sdim       BTy->getKind() != BuiltinType::ULongLong &&
3937218893Sdim       BTy->getKind() != BuiltinType::Float)) {
3938218893Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3939218893Sdim    Attr.setInvalid();
3940218893Sdim    return;
3941218893Sdim  }
3942218893Sdim  // The total size of the vector must be 64 or 128 bits.
3943218893Sdim  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3944218893Sdim  unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3945218893Sdim  unsigned vecSize = typeSize * numElts;
3946218893Sdim  if (vecSize != 64 && vecSize != 128) {
3947218893Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3948218893Sdim    Attr.setInvalid();
3949218893Sdim    return;
3950218893Sdim  }
3951218893Sdim
3952218893Sdim  CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3953218893Sdim}
3954218893Sdim
3955218893Sdimstatic void processTypeAttrs(TypeProcessingState &state, QualType &type,
3956218893Sdim                             bool isDeclSpec, AttributeList *attrs) {
3957193326Sed  // Scan through and apply attributes to this type where it makes sense.  Some
3958193326Sed  // attributes (such as __address_space__, __vector_size__, etc) apply to the
3959193326Sed  // type, but others can be present in the type specifiers even though they
3960193326Sed  // apply to the decl.  Here we apply type attributes and ignore the rest.
3961218893Sdim
3962218893Sdim  AttributeList *next;
3963218893Sdim  do {
3964218893Sdim    AttributeList &attr = *attrs;
3965218893Sdim    next = attr.getNext();
3966218893Sdim
3967207619Srdivacky    // Skip attributes that were marked to be invalid.
3968218893Sdim    if (attr.isInvalid())
3969207619Srdivacky      continue;
3970207619Srdivacky
3971207619Srdivacky    // If this is an attribute we can handle, do so now,
3972207619Srdivacky    // otherwise, add it to the FnAttrs list for rechaining.
3973218893Sdim    switch (attr.getKind()) {
3974193326Sed    default: break;
3975203955Srdivacky
3976226633Sdim    case AttributeList::AT_may_alias:
3977226633Sdim      // FIXME: This attribute needs to actually be handled, but if we ignore
3978226633Sdim      // it it breaks large amounts of Linux software.
3979226633Sdim      attr.setUsedAsTypeAttr();
3980226633Sdim      break;
3981193326Sed    case AttributeList::AT_address_space:
3982218893Sdim      HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
3983226633Sdim      attr.setUsedAsTypeAttr();
3984193326Sed      break;
3985218893Sdim    OBJC_POINTER_TYPE_ATTRS_CASELIST:
3986218893Sdim      if (!handleObjCPointerTypeAttr(state, attr, type))
3987218893Sdim        distributeObjCPointerTypeAttr(state, attr, type);
3988226633Sdim      attr.setUsedAsTypeAttr();
3989193326Sed      break;
3990203955Srdivacky    case AttributeList::AT_vector_size:
3991218893Sdim      HandleVectorSizeAttr(type, attr, state.getSema());
3992226633Sdim      attr.setUsedAsTypeAttr();
3993203955Srdivacky      break;
3994224145Sdim    case AttributeList::AT_ext_vector_type:
3995224145Sdim      if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
3996224145Sdim            != DeclSpec::SCS_typedef)
3997224145Sdim        HandleExtVectorTypeAttr(type, attr, state.getSema());
3998226633Sdim      attr.setUsedAsTypeAttr();
3999224145Sdim      break;
4000218893Sdim    case AttributeList::AT_neon_vector_type:
4001218893Sdim      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4002218893Sdim                               VectorType::NeonVector, "neon_vector_type");
4003226633Sdim      attr.setUsedAsTypeAttr();
4004218893Sdim      break;
4005218893Sdim    case AttributeList::AT_neon_polyvector_type:
4006218893Sdim      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4007218893Sdim                               VectorType::NeonPolyVector,
4008218893Sdim                               "neon_polyvector_type");
4009226633Sdim      attr.setUsedAsTypeAttr();
4010218893Sdim      break;
4011221345Sdim    case AttributeList::AT_opencl_image_access:
4012221345Sdim      HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
4013226633Sdim      attr.setUsedAsTypeAttr();
4014221345Sdim      break;
4015221345Sdim
4016224145Sdim    case AttributeList::AT_ns_returns_retained:
4017234353Sdim      if (!state.getSema().getLangOpts().ObjCAutoRefCount)
4018224145Sdim	break;
4019224145Sdim      // fallthrough into the function attrs
4020224145Sdim
4021218893Sdim    FUNCTION_TYPE_ATTRS_CASELIST:
4022226633Sdim      attr.setUsedAsTypeAttr();
4023226633Sdim
4024218893Sdim      // Never process function type attributes as part of the
4025218893Sdim      // declaration-specifiers.
4026218893Sdim      if (isDeclSpec)
4027218893Sdim        distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4028218893Sdim
4029218893Sdim      // Otherwise, handle the possible delays.
4030218893Sdim      else if (!handleFunctionTypeAttr(state, attr, type))
4031218893Sdim        distributeFunctionTypeAttr(state, attr, type);
4032198092Srdivacky      break;
4033193326Sed    }
4034218893Sdim  } while ((attrs = next));
4035193326Sed}
4036193326Sed
4037223017Sdim/// \brief Ensure that the type of the given expression is complete.
4038223017Sdim///
4039223017Sdim/// This routine checks whether the expression \p E has a complete type. If the
4040223017Sdim/// expression refers to an instantiable construct, that instantiation is
4041223017Sdim/// performed as needed to complete its type. Furthermore
4042223017Sdim/// Sema::RequireCompleteType is called for the expression's type (or in the
4043223017Sdim/// case of a reference type, the referred-to type).
4044223017Sdim///
4045223017Sdim/// \param E The expression whose type is required to be complete.
4046223017Sdim/// \param PD The partial diagnostic that will be printed out if the type cannot
4047223017Sdim/// be completed.
4048223017Sdim///
4049223017Sdim/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4050223017Sdim/// otherwise.
4051223017Sdimbool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
4052223017Sdim                                   std::pair<SourceLocation,
4053223017Sdim                                             PartialDiagnostic> Note) {
4054223017Sdim  QualType T = E->getType();
4055223017Sdim
4056223017Sdim  // Fast path the case where the type is already complete.
4057223017Sdim  if (!T->isIncompleteType())
4058223017Sdim    return false;
4059223017Sdim
4060223017Sdim  // Incomplete array types may be completed by the initializer attached to
4061223017Sdim  // their definitions. For static data members of class templates we need to
4062223017Sdim  // instantiate the definition to get this initializer and complete the type.
4063223017Sdim  if (T->isIncompleteArrayType()) {
4064223017Sdim    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4065223017Sdim      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4066223017Sdim        if (Var->isStaticDataMember() &&
4067223017Sdim            Var->getInstantiatedFromStaticDataMember()) {
4068223017Sdim
4069223017Sdim          MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4070223017Sdim          assert(MSInfo && "Missing member specialization information?");
4071223017Sdim          if (MSInfo->getTemplateSpecializationKind()
4072223017Sdim                != TSK_ExplicitSpecialization) {
4073223017Sdim            // If we don't already have a point of instantiation, this is it.
4074223017Sdim            if (MSInfo->getPointOfInstantiation().isInvalid()) {
4075223017Sdim              MSInfo->setPointOfInstantiation(E->getLocStart());
4076223017Sdim
4077223017Sdim              // This is a modification of an existing AST node. Notify
4078223017Sdim              // listeners.
4079223017Sdim              if (ASTMutationListener *L = getASTMutationListener())
4080223017Sdim                L->StaticDataMemberInstantiated(Var);
4081223017Sdim            }
4082223017Sdim
4083223017Sdim            InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
4084223017Sdim
4085223017Sdim            // Update the type to the newly instantiated definition's type both
4086223017Sdim            // here and within the expression.
4087223017Sdim            if (VarDecl *Def = Var->getDefinition()) {
4088223017Sdim              DRE->setDecl(Def);
4089223017Sdim              T = Def->getType();
4090223017Sdim              DRE->setType(T);
4091223017Sdim              E->setType(T);
4092223017Sdim            }
4093223017Sdim          }
4094223017Sdim
4095223017Sdim          // We still go on to try to complete the type independently, as it
4096223017Sdim          // may also require instantiations or diagnostics if it remains
4097223017Sdim          // incomplete.
4098223017Sdim        }
4099223017Sdim      }
4100223017Sdim    }
4101223017Sdim  }
4102223017Sdim
4103223017Sdim  // FIXME: Are there other cases which require instantiating something other
4104223017Sdim  // than the type to complete the type of an expression?
4105223017Sdim
4106223017Sdim  // Look through reference types and complete the referred type.
4107223017Sdim  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4108223017Sdim    T = Ref->getPointeeType();
4109223017Sdim
4110223017Sdim  return RequireCompleteType(E->getExprLoc(), T, PD, Note);
4111223017Sdim}
4112223017Sdim
4113198092Srdivacky/// @brief Ensure that the type T is a complete type.
4114193326Sed///
4115193326Sed/// This routine checks whether the type @p T is complete in any
4116193326Sed/// context where a complete type is required. If @p T is a complete
4117193326Sed/// type, returns false. If @p T is a class template specialization,
4118193326Sed/// this routine then attempts to perform class template
4119193326Sed/// instantiation. If instantiation fails, or if @p T is incomplete
4120193326Sed/// and cannot be completed, issues the diagnostic @p diag (giving it
4121193326Sed/// the type @p T) and returns true.
4122193326Sed///
4123193326Sed/// @param Loc  The location in the source that the incomplete type
4124193326Sed/// diagnostic should refer to.
4125193326Sed///
4126193326Sed/// @param T  The type that this routine is examining for completeness.
4127193326Sed///
4128198092Srdivacky/// @param PD The partial diagnostic that will be printed out if T is not a
4129198092Srdivacky/// complete type.
4130193326Sed///
4131193326Sed/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4132193326Sed/// @c false otherwise.
4133198092Srdivackybool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4134198092Srdivacky                               const PartialDiagnostic &PD,
4135198092Srdivacky                               std::pair<SourceLocation,
4136198092Srdivacky                                         PartialDiagnostic> Note) {
4137198092Srdivacky  unsigned diag = PD.getDiagID();
4138198092Srdivacky
4139198398Srdivacky  // FIXME: Add this assertion to make sure we always get instantiation points.
4140198398Srdivacky  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
4141193326Sed  // FIXME: Add this assertion to help us flush out problems with
4142193326Sed  // checking for dependent types and type-dependent expressions.
4143193326Sed  //
4144198092Srdivacky  //  assert(!T->isDependentType() &&
4145193326Sed  //         "Can't ask whether a dependent type is complete");
4146193326Sed
4147193326Sed  // If we have a complete type, we're done.
4148234353Sdim  NamedDecl *Def = 0;
4149234353Sdim  if (!T->isIncompleteType(&Def)) {
4150234353Sdim    // If we know about the definition but it is not visible, complain.
4151234353Sdim    if (diag != 0 && Def && !LookupResult::isVisible(Def)) {
4152234353Sdim      // Suppress this error outside of a SFINAE context if we've already
4153234353Sdim      // emitted the error once for this type. There's no usefulness in
4154234353Sdim      // repeating the diagnostic.
4155234353Sdim      // FIXME: Add a Fix-It that imports the corresponding module or includes
4156234353Sdim      // the header.
4157234353Sdim      if (isSFINAEContext() || HiddenDefinitions.insert(Def)) {
4158234353Sdim        Diag(Loc, diag::err_module_private_definition) << T;
4159234353Sdim        Diag(Def->getLocation(), diag::note_previous_definition);
4160234353Sdim      }
4161234353Sdim    }
4162234353Sdim
4163193326Sed    return false;
4164234353Sdim  }
4165193326Sed
4166234353Sdim  const TagType *Tag = T->getAs<TagType>();
4167234353Sdim  const ObjCInterfaceType *IFace = 0;
4168234353Sdim
4169234353Sdim  if (Tag) {
4170234353Sdim    // Avoid diagnosing invalid decls as incomplete.
4171234353Sdim    if (Tag->getDecl()->isInvalidDecl())
4172234353Sdim      return true;
4173234353Sdim
4174234353Sdim    // Give the external AST source a chance to complete the type.
4175234353Sdim    if (Tag->getDecl()->hasExternalLexicalStorage()) {
4176234353Sdim      Context.getExternalSource()->CompleteType(Tag->getDecl());
4177234353Sdim      if (!Tag->isIncompleteType())
4178234353Sdim        return false;
4179234353Sdim    }
4180234353Sdim  }
4181234353Sdim  else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4182234353Sdim    // Avoid diagnosing invalid decls as incomplete.
4183234353Sdim    if (IFace->getDecl()->isInvalidDecl())
4184234353Sdim      return true;
4185234353Sdim
4186234353Sdim    // Give the external AST source a chance to complete the type.
4187234353Sdim    if (IFace->getDecl()->hasExternalLexicalStorage()) {
4188234353Sdim      Context.getExternalSource()->CompleteType(IFace->getDecl());
4189234353Sdim      if (!IFace->isIncompleteType())
4190234353Sdim        return false;
4191234353Sdim    }
4192234353Sdim  }
4193234353Sdim
4194193326Sed  // If we have a class template specialization or a class member of a
4195198954Srdivacky  // class template specialization, or an array with known size of such,
4196198954Srdivacky  // try to instantiate it.
4197198954Srdivacky  QualType MaybeTemplate = T;
4198235864Sdim  while (const ConstantArrayType *Array
4199235864Sdim           = Context.getAsConstantArrayType(MaybeTemplate))
4200198954Srdivacky    MaybeTemplate = Array->getElementType();
4201198954Srdivacky  if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
4202193326Sed    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
4203193326Sed          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
4204198893Srdivacky      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4205198893Srdivacky        return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
4206198092Srdivacky                                                      TSK_ImplicitInstantiation,
4207198092Srdivacky                                                      /*Complain=*/diag != 0);
4208198092Srdivacky    } else if (CXXRecordDecl *Rec
4209193326Sed                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
4210234353Sdim      CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
4211234353Sdim      if (!Rec->isBeingDefined() && Pattern) {
4212234353Sdim        MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
4213234353Sdim        assert(MSI && "Missing member specialization information?");
4214198092Srdivacky        // This record was instantiated from a class within a template.
4215234353Sdim        if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
4216198092Srdivacky          return InstantiateClass(Loc, Rec, Pattern,
4217198092Srdivacky                                  getTemplateInstantiationArgs(Rec),
4218198092Srdivacky                                  TSK_ImplicitInstantiation,
4219198092Srdivacky                                  /*Complain=*/diag != 0);
4220193326Sed      }
4221193326Sed    }
4222193326Sed  }
4223193326Sed
4224198092Srdivacky  if (diag == 0)
4225198092Srdivacky    return true;
4226234353Sdim
4227193326Sed  // We have an incomplete type. Produce a diagnostic.
4228198092Srdivacky  Diag(Loc, PD) << T;
4229234353Sdim
4230198092Srdivacky  // If we have a note, produce it.
4231198092Srdivacky  if (!Note.first.isInvalid())
4232198092Srdivacky    Diag(Note.first, Note.second);
4233198092Srdivacky
4234193326Sed  // If the type was a forward declaration of a class/struct/union
4235206084Srdivacky  // type, produce a note.
4236193326Sed  if (Tag && !Tag->getDecl()->isInvalidDecl())
4237198092Srdivacky    Diag(Tag->getDecl()->getLocation(),
4238193326Sed         Tag->isBeingDefined() ? diag::note_type_being_defined
4239193326Sed                               : diag::note_forward_declaration)
4240234353Sdim      << QualType(Tag, 0);
4241234353Sdim
4242234353Sdim  // If the Objective-C class was a forward declaration, produce a note.
4243234353Sdim  if (IFace && !IFace->getDecl()->isInvalidDecl())
4244234353Sdim    Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
4245193326Sed
4246193326Sed  return true;
4247193326Sed}
4248193326Sed
4249206084Srdivackybool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4250206084Srdivacky                               const PartialDiagnostic &PD) {
4251206084Srdivacky  return RequireCompleteType(Loc, T, PD,
4252206084Srdivacky                             std::make_pair(SourceLocation(), PDiag(0)));
4253206084Srdivacky}
4254206084Srdivacky
4255206084Srdivackybool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4256206084Srdivacky                               unsigned DiagID) {
4257206084Srdivacky  return RequireCompleteType(Loc, T, PDiag(DiagID),
4258206084Srdivacky                             std::make_pair(SourceLocation(), PDiag(0)));
4259206084Srdivacky}
4260206084Srdivacky
4261226633Sdim/// @brief Ensure that the type T is a literal type.
4262226633Sdim///
4263226633Sdim/// This routine checks whether the type @p T is a literal type. If @p T is an
4264226633Sdim/// incomplete type, an attempt is made to complete it. If @p T is a literal
4265226633Sdim/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4266226633Sdim/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4267226633Sdim/// it the type @p T), along with notes explaining why the type is not a
4268226633Sdim/// literal type, and returns true.
4269226633Sdim///
4270226633Sdim/// @param Loc  The location in the source that the non-literal type
4271226633Sdim/// diagnostic should refer to.
4272226633Sdim///
4273226633Sdim/// @param T  The type that this routine is examining for literalness.
4274226633Sdim///
4275226633Sdim/// @param PD The partial diagnostic that will be printed out if T is not a
4276226633Sdim/// literal type.
4277226633Sdim///
4278226633Sdim/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4279226633Sdim/// @c false otherwise.
4280226633Sdimbool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
4281234353Sdim                              const PartialDiagnostic &PD) {
4282226633Sdim  assert(!T->isDependentType() && "type should not be dependent");
4283226633Sdim
4284234353Sdim  QualType ElemType = Context.getBaseElementType(T);
4285234353Sdim  RequireCompleteType(Loc, ElemType, 0);
4286234353Sdim
4287234353Sdim  if (T->isLiteralType())
4288226633Sdim    return false;
4289226633Sdim
4290226633Sdim  if (PD.getDiagID() == 0)
4291226633Sdim    return true;
4292226633Sdim
4293226633Sdim  Diag(Loc, PD) << T;
4294226633Sdim
4295226633Sdim  if (T->isVariableArrayType())
4296226633Sdim    return true;
4297226633Sdim
4298234353Sdim  const RecordType *RT = ElemType->getAs<RecordType>();
4299226633Sdim  if (!RT)
4300226633Sdim    return true;
4301226633Sdim
4302226633Sdim  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4303226633Sdim
4304234353Sdim  // FIXME: Better diagnostic for incomplete class?
4305234353Sdim  if (!RD->isCompleteDefinition())
4306234353Sdim    return true;
4307234353Sdim
4308226633Sdim  // If the class has virtual base classes, then it's not an aggregate, and
4309234353Sdim  // cannot have any constexpr constructors or a trivial default constructor,
4310234353Sdim  // so is non-literal. This is better to diagnose than the resulting absence
4311234353Sdim  // of constexpr constructors.
4312226633Sdim  if (RD->getNumVBases()) {
4313226633Sdim    Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
4314226633Sdim      << RD->isStruct() << RD->getNumVBases();
4315226633Sdim    for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4316226633Sdim           E = RD->vbases_end(); I != E; ++I)
4317234353Sdim      Diag(I->getLocStart(),
4318226633Sdim           diag::note_constexpr_virtual_base_here) << I->getSourceRange();
4319234353Sdim  } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
4320234353Sdim             !RD->hasTrivialDefaultConstructor()) {
4321226633Sdim    Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
4322226633Sdim  } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4323226633Sdim    for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4324226633Sdim         E = RD->bases_end(); I != E; ++I) {
4325226633Sdim      if (!I->getType()->isLiteralType()) {
4326234353Sdim        Diag(I->getLocStart(),
4327226633Sdim             diag::note_non_literal_base_class)
4328226633Sdim          << RD << I->getType() << I->getSourceRange();
4329226633Sdim        return true;
4330226633Sdim      }
4331226633Sdim    }
4332226633Sdim    for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4333226633Sdim         E = RD->field_end(); I != E; ++I) {
4334234353Sdim      if (!(*I)->getType()->isLiteralType() ||
4335234353Sdim          (*I)->getType().isVolatileQualified()) {
4336226633Sdim        Diag((*I)->getLocation(), diag::note_non_literal_field)
4337234353Sdim          << RD << (*I) << (*I)->getType()
4338234353Sdim          << (*I)->getType().isVolatileQualified();
4339226633Sdim        return true;
4340226633Sdim      }
4341226633Sdim    }
4342226633Sdim  } else if (!RD->hasTrivialDestructor()) {
4343226633Sdim    // All fields and bases are of literal types, so have trivial destructors.
4344226633Sdim    // If this class's destructor is non-trivial it must be user-declared.
4345226633Sdim    CXXDestructorDecl *Dtor = RD->getDestructor();
4346226633Sdim    assert(Dtor && "class has literal fields and bases but no dtor?");
4347226633Sdim    if (!Dtor)
4348226633Sdim      return true;
4349226633Sdim
4350226633Sdim    Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4351226633Sdim         diag::note_non_literal_user_provided_dtor :
4352226633Sdim         diag::note_non_literal_nontrivial_dtor) << RD;
4353226633Sdim  }
4354226633Sdim
4355226633Sdim  return true;
4356226633Sdim}
4357226633Sdim
4358208600Srdivacky/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4359208600Srdivacky/// and qualified by the nested-name-specifier contained in SS.
4360208600SrdivackyQualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4361208600Srdivacky                                 const CXXScopeSpec &SS, QualType T) {
4362208600Srdivacky  if (T.isNull())
4363193326Sed    return T;
4364208600Srdivacky  NestedNameSpecifier *NNS;
4365208600Srdivacky  if (SS.isValid())
4366208600Srdivacky    NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4367208600Srdivacky  else {
4368208600Srdivacky    if (Keyword == ETK_None)
4369208600Srdivacky      return T;
4370208600Srdivacky    NNS = 0;
4371208600Srdivacky  }
4372208600Srdivacky  return Context.getElaboratedType(Keyword, NNS, T);
4373193326Sed}
4374195341Sed
4375218893SdimQualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
4376221345Sdim  ExprResult ER = CheckPlaceholderExpr(E);
4377218893Sdim  if (ER.isInvalid()) return QualType();
4378218893Sdim  E = ER.take();
4379218893Sdim
4380218893Sdim  if (!E->isTypeDependent()) {
4381218893Sdim    QualType T = E->getType();
4382218893Sdim    if (const TagType *TT = T->getAs<TagType>())
4383218893Sdim      DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
4384201361Srdivacky  }
4385195341Sed  return Context.getTypeOfExprType(E);
4386195341Sed}
4387195341Sed
4388234353Sdim/// getDecltypeForExpr - Given an expr, will return the decltype for
4389234353Sdim/// that expression, according to the rules in C++11
4390234353Sdim/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
4391234353Sdimstatic QualType getDecltypeForExpr(Sema &S, Expr *E) {
4392234353Sdim  if (E->isTypeDependent())
4393234353Sdim    return S.Context.DependentTy;
4394234353Sdim
4395234353Sdim  // C++11 [dcl.type.simple]p4:
4396234353Sdim  //   The type denoted by decltype(e) is defined as follows:
4397234353Sdim  //
4398234353Sdim  //     - if e is an unparenthesized id-expression or an unparenthesized class
4399234353Sdim  //       member access (5.2.5), decltype(e) is the type of the entity named
4400234353Sdim  //       by e. If there is no such entity, or if e names a set of overloaded
4401234353Sdim  //       functions, the program is ill-formed;
4402234353Sdim  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4403234353Sdim    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
4404234353Sdim      return VD->getType();
4405234353Sdim  }
4406234353Sdim  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
4407234353Sdim    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4408234353Sdim      return FD->getType();
4409234353Sdim  }
4410234353Sdim
4411234353Sdim  // C++11 [expr.lambda.prim]p18:
4412234353Sdim  //   Every occurrence of decltype((x)) where x is a possibly
4413234353Sdim  //   parenthesized id-expression that names an entity of automatic
4414234353Sdim  //   storage duration is treated as if x were transformed into an
4415234353Sdim  //   access to a corresponding data member of the closure type that
4416234353Sdim  //   would have been declared if x were an odr-use of the denoted
4417234353Sdim  //   entity.
4418234353Sdim  using namespace sema;
4419234353Sdim  if (S.getCurLambda()) {
4420234353Sdim    if (isa<ParenExpr>(E)) {
4421234353Sdim      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4422234353Sdim        if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4423234353Sdim          QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
4424234353Sdim          if (!T.isNull())
4425234353Sdim            return S.Context.getLValueReferenceType(T);
4426234353Sdim        }
4427234353Sdim      }
4428234353Sdim    }
4429234353Sdim  }
4430234353Sdim
4431234353Sdim
4432234353Sdim  // C++11 [dcl.type.simple]p4:
4433234353Sdim  //   [...]
4434234353Sdim  QualType T = E->getType();
4435234353Sdim  switch (E->getValueKind()) {
4436234353Sdim  //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
4437234353Sdim  //       type of e;
4438234353Sdim  case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
4439234353Sdim  //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
4440234353Sdim  //       type of e;
4441234353Sdim  case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
4442234353Sdim  //  - otherwise, decltype(e) is the type of e.
4443234353Sdim  case VK_RValue: break;
4444234353Sdim  }
4445234353Sdim
4446234353Sdim  return T;
4447234353Sdim}
4448234353Sdim
4449218893SdimQualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
4450221345Sdim  ExprResult ER = CheckPlaceholderExpr(E);
4451218893Sdim  if (ER.isInvalid()) return QualType();
4452218893Sdim  E = ER.take();
4453201361Srdivacky
4454234353Sdim  return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
4455195341Sed}
4456223017Sdim
4457223017SdimQualType Sema::BuildUnaryTransformType(QualType BaseType,
4458223017Sdim                                       UnaryTransformType::UTTKind UKind,
4459223017Sdim                                       SourceLocation Loc) {
4460223017Sdim  switch (UKind) {
4461223017Sdim  case UnaryTransformType::EnumUnderlyingType:
4462223017Sdim    if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4463223017Sdim      Diag(Loc, diag::err_only_enums_have_underlying_types);
4464223017Sdim      return QualType();
4465223017Sdim    } else {
4466223017Sdim      QualType Underlying = BaseType;
4467223017Sdim      if (!BaseType->isDependentType()) {
4468223017Sdim        EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4469223017Sdim        assert(ED && "EnumType has no EnumDecl");
4470223017Sdim        DiagnoseUseOfDecl(ED, Loc);
4471223017Sdim        Underlying = ED->getIntegerType();
4472223017Sdim      }
4473223017Sdim      assert(!Underlying.isNull());
4474223017Sdim      return Context.getUnaryTransformType(BaseType, Underlying,
4475223017Sdim                                        UnaryTransformType::EnumUnderlyingType);
4476223017Sdim    }
4477223017Sdim  }
4478223017Sdim  llvm_unreachable("unknown unary transform type");
4479223017Sdim}
4480226633Sdim
4481226633SdimQualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
4482226633Sdim  if (!T->isDependentType()) {
4483234353Sdim    // FIXME: It isn't entirely clear whether incomplete atomic types
4484234353Sdim    // are allowed or not; for simplicity, ban them for the moment.
4485234353Sdim    if (RequireCompleteType(Loc, T,
4486234353Sdim                            PDiag(diag::err_atomic_specifier_bad_type) << 0))
4487234353Sdim      return QualType();
4488234353Sdim
4489226633Sdim    int DisallowedKind = -1;
4490234353Sdim    if (T->isArrayType())
4491226633Sdim      DisallowedKind = 1;
4492226633Sdim    else if (T->isFunctionType())
4493226633Sdim      DisallowedKind = 2;
4494226633Sdim    else if (T->isReferenceType())
4495226633Sdim      DisallowedKind = 3;
4496226633Sdim    else if (T->isAtomicType())
4497226633Sdim      DisallowedKind = 4;
4498226633Sdim    else if (T.hasQualifiers())
4499226633Sdim      DisallowedKind = 5;
4500226633Sdim    else if (!T.isTriviallyCopyableType(Context))
4501226633Sdim      // Some other non-trivially-copyable type (probably a C++ class)
4502226633Sdim      DisallowedKind = 6;
4503226633Sdim
4504226633Sdim    if (DisallowedKind != -1) {
4505226633Sdim      Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
4506226633Sdim      return QualType();
4507226633Sdim    }
4508226633Sdim
4509226633Sdim    // FIXME: Do we need any handling for ARC here?
4510226633Sdim  }
4511226633Sdim
4512226633Sdim  // Build the pointer type.
4513226633Sdim  return Context.getAtomicType(T);
4514226633Sdim}
4515