1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements type-related semantic analysis.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/Basic/OpenCL.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/AST/TypeLocVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/Support/ErrorHandling.h"
32 using namespace clang;
33 
34 /// isOmittedBlockReturnType - Return true if this declarator is missing a
35 /// return type because this is a omitted return type on a block literal.
36 static bool isOmittedBlockReturnType(const Declarator &D) {
37   if (D.getContext() != Declarator::BlockLiteralContext ||
38       D.getDeclSpec().hasTypeSpecifier())
39     return false;
40 
41   if (D.getNumTypeObjects() == 0)
42     return true;   // ^{ ... }
43 
44   if (D.getNumTypeObjects() == 1 &&
45       D.getTypeObject(0).Kind == DeclaratorChunk::Function)
46     return true;   // ^(int X, float Y) { ... }
47 
48   return false;
49 }
50 
51 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
52 /// doesn't apply to the given type.
53 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
54                                      QualType type) {
55   bool useExpansionLoc = false;
56 
57   unsigned diagID = 0;
58   switch (attr.getKind()) {
59   case AttributeList::AT_objc_gc:
60     diagID = diag::warn_pointer_attribute_wrong_type;
61     useExpansionLoc = true;
62     break;
63 
64   case AttributeList::AT_objc_ownership:
65     diagID = diag::warn_objc_object_attribute_wrong_type;
66     useExpansionLoc = true;
67     break;
68 
69   default:
70     // Assume everything else was a function attribute.
71     diagID = diag::warn_function_attribute_wrong_type;
72     break;
73   }
74 
75   SourceLocation loc = attr.getLoc();
76   StringRef name = attr.getName()->getName();
77 
78   // The GC attributes are usually written with macros;  special-case them.
79   if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
80     if (attr.getParameterName()->isStr("strong")) {
81       if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
82     } else if (attr.getParameterName()->isStr("weak")) {
83       if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
84     }
85   }
86 
87   S.Diag(loc, diagID) << name << type;
88 }
89 
90 // objc_gc applies to Objective-C pointers or, otherwise, to the
91 // smallest available pointer type (i.e. 'void*' in 'void**').
92 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
93     case AttributeList::AT_objc_gc: \
94     case AttributeList::AT_objc_ownership
95 
96 // Function type attributes.
97 #define FUNCTION_TYPE_ATTRS_CASELIST \
98     case AttributeList::AT_noreturn: \
99     case AttributeList::AT_cdecl: \
100     case AttributeList::AT_fastcall: \
101     case AttributeList::AT_stdcall: \
102     case AttributeList::AT_thiscall: \
103     case AttributeList::AT_pascal: \
104     case AttributeList::AT_regparm: \
105     case AttributeList::AT_pcs \
106 
107 namespace {
108   /// An object which stores processing state for the entire
109   /// GetTypeForDeclarator process.
110   class TypeProcessingState {
111     Sema &sema;
112 
113     /// The declarator being processed.
114     Declarator &declarator;
115 
116     /// The index of the declarator chunk we're currently processing.
117     /// May be the total number of valid chunks, indicating the
118     /// DeclSpec.
119     unsigned chunkIndex;
120 
121     /// Whether there are non-trivial modifications to the decl spec.
122     bool trivial;
123 
124     /// Whether we saved the attributes in the decl spec.
125     bool hasSavedAttrs;
126 
127     /// The original set of attributes on the DeclSpec.
128     SmallVector<AttributeList*, 2> savedAttrs;
129 
130     /// A list of attributes to diagnose the uselessness of when the
131     /// processing is complete.
132     SmallVector<AttributeList*, 2> ignoredTypeAttrs;
133 
134   public:
135     TypeProcessingState(Sema &sema, Declarator &declarator)
136       : sema(sema), declarator(declarator),
137         chunkIndex(declarator.getNumTypeObjects()),
138         trivial(true), hasSavedAttrs(false) {}
139 
140     Sema &getSema() const {
141       return sema;
142     }
143 
144     Declarator &getDeclarator() const {
145       return declarator;
146     }
147 
148     unsigned getCurrentChunkIndex() const {
149       return chunkIndex;
150     }
151 
152     void setCurrentChunkIndex(unsigned idx) {
153       assert(idx <= declarator.getNumTypeObjects());
154       chunkIndex = idx;
155     }
156 
157     AttributeList *&getCurrentAttrListRef() const {
158       assert(chunkIndex <= declarator.getNumTypeObjects());
159       if (chunkIndex == declarator.getNumTypeObjects())
160         return getMutableDeclSpec().getAttributes().getListRef();
161       return declarator.getTypeObject(chunkIndex).getAttrListRef();
162     }
163 
164     /// Save the current set of attributes on the DeclSpec.
165     void saveDeclSpecAttrs() {
166       // Don't try to save them multiple times.
167       if (hasSavedAttrs) return;
168 
169       DeclSpec &spec = getMutableDeclSpec();
170       for (AttributeList *attr = spec.getAttributes().getList(); attr;
171              attr = attr->getNext())
172         savedAttrs.push_back(attr);
173       trivial &= savedAttrs.empty();
174       hasSavedAttrs = true;
175     }
176 
177     /// Record that we had nowhere to put the given type attribute.
178     /// We will diagnose such attributes later.
179     void addIgnoredTypeAttr(AttributeList &attr) {
180       ignoredTypeAttrs.push_back(&attr);
181     }
182 
183     /// Diagnose all the ignored type attributes, given that the
184     /// declarator worked out to the given type.
185     void diagnoseIgnoredTypeAttrs(QualType type) const {
186       for (SmallVectorImpl<AttributeList*>::const_iterator
187              i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
188            i != e; ++i)
189         diagnoseBadTypeAttribute(getSema(), **i, type);
190     }
191 
192     ~TypeProcessingState() {
193       if (trivial) return;
194 
195       restoreDeclSpecAttrs();
196     }
197 
198   private:
199     DeclSpec &getMutableDeclSpec() const {
200       return const_cast<DeclSpec&>(declarator.getDeclSpec());
201     }
202 
203     void restoreDeclSpecAttrs() {
204       assert(hasSavedAttrs);
205 
206       if (savedAttrs.empty()) {
207         getMutableDeclSpec().getAttributes().set(0);
208         return;
209       }
210 
211       getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
212       for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
213         savedAttrs[i]->setNext(savedAttrs[i+1]);
214       savedAttrs.back()->setNext(0);
215     }
216   };
217 
218   /// Basically std::pair except that we really want to avoid an
219   /// implicit operator= for safety concerns.  It's also a minor
220   /// link-time optimization for this to be a private type.
221   struct AttrAndList {
222     /// The attribute.
223     AttributeList &first;
224 
225     /// The head of the list the attribute is currently in.
226     AttributeList *&second;
227 
228     AttrAndList(AttributeList &attr, AttributeList *&head)
229       : first(attr), second(head) {}
230   };
231 }
232 
233 namespace llvm {
234   template <> struct isPodLike<AttrAndList> {
235     static const bool value = true;
236   };
237 }
238 
239 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
240   attr.setNext(head);
241   head = &attr;
242 }
243 
244 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
245   if (head == &attr) {
246     head = attr.getNext();
247     return;
248   }
249 
250   AttributeList *cur = head;
251   while (true) {
252     assert(cur && cur->getNext() && "ran out of attrs?");
253     if (cur->getNext() == &attr) {
254       cur->setNext(attr.getNext());
255       return;
256     }
257     cur = cur->getNext();
258   }
259 }
260 
261 static void moveAttrFromListToList(AttributeList &attr,
262                                    AttributeList *&fromList,
263                                    AttributeList *&toList) {
264   spliceAttrOutOfList(attr, fromList);
265   spliceAttrIntoList(attr, toList);
266 }
267 
268 static void processTypeAttrs(TypeProcessingState &state,
269                              QualType &type, bool isDeclSpec,
270                              AttributeList *attrs);
271 
272 static bool handleFunctionTypeAttr(TypeProcessingState &state,
273                                    AttributeList &attr,
274                                    QualType &type);
275 
276 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
277                                  AttributeList &attr, QualType &type);
278 
279 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
280                                        AttributeList &attr, QualType &type);
281 
282 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
283                                       AttributeList &attr, QualType &type) {
284   if (attr.getKind() == AttributeList::AT_objc_gc)
285     return handleObjCGCTypeAttr(state, attr, type);
286   assert(attr.getKind() == AttributeList::AT_objc_ownership);
287   return handleObjCOwnershipTypeAttr(state, attr, type);
288 }
289 
290 /// Given that an objc_gc attribute was written somewhere on a
291 /// declaration *other* than on the declarator itself (for which, use
292 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
293 /// didn't apply in whatever position it was written in, try to move
294 /// it to a more appropriate position.
295 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
296                                           AttributeList &attr,
297                                           QualType type) {
298   Declarator &declarator = state.getDeclarator();
299   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
300     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
301     switch (chunk.Kind) {
302     case DeclaratorChunk::Pointer:
303     case DeclaratorChunk::BlockPointer:
304       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
305                              chunk.getAttrListRef());
306       return;
307 
308     case DeclaratorChunk::Paren:
309     case DeclaratorChunk::Array:
310       continue;
311 
312     // Don't walk through these.
313     case DeclaratorChunk::Reference:
314     case DeclaratorChunk::Function:
315     case DeclaratorChunk::MemberPointer:
316       goto error;
317     }
318   }
319  error:
320 
321   diagnoseBadTypeAttribute(state.getSema(), attr, type);
322 }
323 
324 /// Distribute an objc_gc type attribute that was written on the
325 /// declarator.
326 static void
327 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
328                                             AttributeList &attr,
329                                             QualType &declSpecType) {
330   Declarator &declarator = state.getDeclarator();
331 
332   // objc_gc goes on the innermost pointer to something that's not a
333   // pointer.
334   unsigned innermost = -1U;
335   bool considerDeclSpec = true;
336   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
337     DeclaratorChunk &chunk = declarator.getTypeObject(i);
338     switch (chunk.Kind) {
339     case DeclaratorChunk::Pointer:
340     case DeclaratorChunk::BlockPointer:
341       innermost = i;
342       continue;
343 
344     case DeclaratorChunk::Reference:
345     case DeclaratorChunk::MemberPointer:
346     case DeclaratorChunk::Paren:
347     case DeclaratorChunk::Array:
348       continue;
349 
350     case DeclaratorChunk::Function:
351       considerDeclSpec = false;
352       goto done;
353     }
354   }
355  done:
356 
357   // That might actually be the decl spec if we weren't blocked by
358   // anything in the declarator.
359   if (considerDeclSpec) {
360     if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
361       // Splice the attribute into the decl spec.  Prevents the
362       // attribute from being applied multiple times and gives
363       // the source-location-filler something to work with.
364       state.saveDeclSpecAttrs();
365       moveAttrFromListToList(attr, declarator.getAttrListRef(),
366                declarator.getMutableDeclSpec().getAttributes().getListRef());
367       return;
368     }
369   }
370 
371   // Otherwise, if we found an appropriate chunk, splice the attribute
372   // into it.
373   if (innermost != -1U) {
374     moveAttrFromListToList(attr, declarator.getAttrListRef(),
375                        declarator.getTypeObject(innermost).getAttrListRef());
376     return;
377   }
378 
379   // Otherwise, diagnose when we're done building the type.
380   spliceAttrOutOfList(attr, declarator.getAttrListRef());
381   state.addIgnoredTypeAttr(attr);
382 }
383 
384 /// A function type attribute was written somewhere in a declaration
385 /// *other* than on the declarator itself or in the decl spec.  Given
386 /// that it didn't apply in whatever position it was written in, try
387 /// to move it to a more appropriate position.
388 static void distributeFunctionTypeAttr(TypeProcessingState &state,
389                                        AttributeList &attr,
390                                        QualType type) {
391   Declarator &declarator = state.getDeclarator();
392 
393   // Try to push the attribute from the return type of a function to
394   // the function itself.
395   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
396     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
397     switch (chunk.Kind) {
398     case DeclaratorChunk::Function:
399       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
400                              chunk.getAttrListRef());
401       return;
402 
403     case DeclaratorChunk::Paren:
404     case DeclaratorChunk::Pointer:
405     case DeclaratorChunk::BlockPointer:
406     case DeclaratorChunk::Array:
407     case DeclaratorChunk::Reference:
408     case DeclaratorChunk::MemberPointer:
409       continue;
410     }
411   }
412 
413   diagnoseBadTypeAttribute(state.getSema(), attr, type);
414 }
415 
416 /// Try to distribute a function type attribute to the innermost
417 /// function chunk or type.  Returns true if the attribute was
418 /// distributed, false if no location was found.
419 static bool
420 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
421                                       AttributeList &attr,
422                                       AttributeList *&attrList,
423                                       QualType &declSpecType) {
424   Declarator &declarator = state.getDeclarator();
425 
426   // Put it on the innermost function chunk, if there is one.
427   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
428     DeclaratorChunk &chunk = declarator.getTypeObject(i);
429     if (chunk.Kind != DeclaratorChunk::Function) continue;
430 
431     moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
432     return true;
433   }
434 
435   if (handleFunctionTypeAttr(state, attr, declSpecType)) {
436     spliceAttrOutOfList(attr, attrList);
437     return true;
438   }
439 
440   return false;
441 }
442 
443 /// A function type attribute was written in the decl spec.  Try to
444 /// apply it somewhere.
445 static void
446 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
447                                        AttributeList &attr,
448                                        QualType &declSpecType) {
449   state.saveDeclSpecAttrs();
450 
451   // Try to distribute to the innermost.
452   if (distributeFunctionTypeAttrToInnermost(state, attr,
453                                             state.getCurrentAttrListRef(),
454                                             declSpecType))
455     return;
456 
457   // If that failed, diagnose the bad attribute when the declarator is
458   // fully built.
459   state.addIgnoredTypeAttr(attr);
460 }
461 
462 /// A function type attribute was written on the declarator.  Try to
463 /// apply it somewhere.
464 static void
465 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
466                                          AttributeList &attr,
467                                          QualType &declSpecType) {
468   Declarator &declarator = state.getDeclarator();
469 
470   // Try to distribute to the innermost.
471   if (distributeFunctionTypeAttrToInnermost(state, attr,
472                                             declarator.getAttrListRef(),
473                                             declSpecType))
474     return;
475 
476   // If that failed, diagnose the bad attribute when the declarator is
477   // fully built.
478   spliceAttrOutOfList(attr, declarator.getAttrListRef());
479   state.addIgnoredTypeAttr(attr);
480 }
481 
482 /// \brief Given that there are attributes written on the declarator
483 /// itself, try to distribute any type attributes to the appropriate
484 /// declarator chunk.
485 ///
486 /// These are attributes like the following:
487 ///   int f ATTR;
488 ///   int (f ATTR)();
489 /// but not necessarily this:
490 ///   int f() ATTR;
491 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
492                                               QualType &declSpecType) {
493   // Collect all the type attributes from the declarator itself.
494   assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
495   AttributeList *attr = state.getDeclarator().getAttributes();
496   AttributeList *next;
497   do {
498     next = attr->getNext();
499 
500     switch (attr->getKind()) {
501     OBJC_POINTER_TYPE_ATTRS_CASELIST:
502       distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
503       break;
504 
505     case AttributeList::AT_ns_returns_retained:
506       if (!state.getSema().getLangOptions().ObjCAutoRefCount)
507         break;
508       // fallthrough
509 
510     FUNCTION_TYPE_ATTRS_CASELIST:
511       distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
512       break;
513 
514     default:
515       break;
516     }
517   } while ((attr = next));
518 }
519 
520 /// Add a synthetic '()' to a block-literal declarator if it is
521 /// required, given the return type.
522 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
523                                           QualType declSpecType) {
524   Declarator &declarator = state.getDeclarator();
525 
526   // First, check whether the declarator would produce a function,
527   // i.e. whether the innermost semantic chunk is a function.
528   if (declarator.isFunctionDeclarator()) {
529     // If so, make that declarator a prototyped declarator.
530     declarator.getFunctionTypeInfo().hasPrototype = true;
531     return;
532   }
533 
534   // If there are any type objects, the type as written won't name a
535   // function, regardless of the decl spec type.  This is because a
536   // block signature declarator is always an abstract-declarator, and
537   // abstract-declarators can't just be parentheses chunks.  Therefore
538   // we need to build a function chunk unless there are no type
539   // objects and the decl spec type is a function.
540   if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
541     return;
542 
543   // Note that there *are* cases with invalid declarators where
544   // declarators consist solely of parentheses.  In general, these
545   // occur only in failed efforts to make function declarators, so
546   // faking up the function chunk is still the right thing to do.
547 
548   // Otherwise, we need to fake up a function declarator.
549   SourceLocation loc = declarator.getSourceRange().getBegin();
550 
551   // ...and *prepend* it to the declarator.
552   declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
553                              /*proto*/ true,
554                              /*variadic*/ false, SourceLocation(),
555                              /*args*/ 0, 0,
556                              /*type quals*/ 0,
557                              /*ref-qualifier*/true, SourceLocation(),
558                              /*mutable qualifier*/SourceLocation(),
559                              /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
560                              /*parens*/ loc, loc,
561                              declarator));
562 
563   // For consistency, make sure the state still has us as processing
564   // the decl spec.
565   assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
566   state.setCurrentChunkIndex(declarator.getNumTypeObjects());
567 }
568 
569 /// \brief Convert the specified declspec to the appropriate type
570 /// object.
571 /// \param D  the declarator containing the declaration specifier.
572 /// \returns The type described by the declaration specifiers.  This function
573 /// never returns null.
574 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
575   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
576   // checking.
577 
578   Sema &S = state.getSema();
579   Declarator &declarator = state.getDeclarator();
580   const DeclSpec &DS = declarator.getDeclSpec();
581   SourceLocation DeclLoc = declarator.getIdentifierLoc();
582   if (DeclLoc.isInvalid())
583     DeclLoc = DS.getSourceRange().getBegin();
584 
585   ASTContext &Context = S.Context;
586 
587   QualType Result;
588   switch (DS.getTypeSpecType()) {
589   case DeclSpec::TST_void:
590     Result = Context.VoidTy;
591     break;
592   case DeclSpec::TST_char:
593     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
594       Result = Context.CharTy;
595     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
596       Result = Context.SignedCharTy;
597     else {
598       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
599              "Unknown TSS value");
600       Result = Context.UnsignedCharTy;
601     }
602     break;
603   case DeclSpec::TST_wchar:
604     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
605       Result = Context.WCharTy;
606     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
607       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
608         << DS.getSpecifierName(DS.getTypeSpecType());
609       Result = Context.getSignedWCharType();
610     } else {
611       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
612         "Unknown TSS value");
613       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
614         << DS.getSpecifierName(DS.getTypeSpecType());
615       Result = Context.getUnsignedWCharType();
616     }
617     break;
618   case DeclSpec::TST_char16:
619       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
620         "Unknown TSS value");
621       Result = Context.Char16Ty;
622     break;
623   case DeclSpec::TST_char32:
624       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
625         "Unknown TSS value");
626       Result = Context.Char32Ty;
627     break;
628   case DeclSpec::TST_unspecified:
629     // "<proto1,proto2>" is an objc qualified ID with a missing id.
630     if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
631       Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
632                                          (ObjCProtocolDecl**)PQ,
633                                          DS.getNumProtocolQualifiers());
634       Result = Context.getObjCObjectPointerType(Result);
635       break;
636     }
637 
638     // If this is a missing declspec in a block literal return context, then it
639     // is inferred from the return statements inside the block.
640     if (isOmittedBlockReturnType(declarator)) {
641       Result = Context.DependentTy;
642       break;
643     }
644 
645     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
646     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
647     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
648     // Note that the one exception to this is function definitions, which are
649     // allowed to be completely missing a declspec.  This is handled in the
650     // parser already though by it pretending to have seen an 'int' in this
651     // case.
652     if (S.getLangOptions().ImplicitInt) {
653       // In C89 mode, we only warn if there is a completely missing declspec
654       // when one is not allowed.
655       if (DS.isEmpty()) {
656         S.Diag(DeclLoc, diag::ext_missing_declspec)
657           << DS.getSourceRange()
658         << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
659       }
660     } else if (!DS.hasTypeSpecifier()) {
661       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
662       // "At least one type specifier shall be given in the declaration
663       // specifiers in each declaration, and in the specifier-qualifier list in
664       // each struct declaration and type name."
665       // FIXME: Does Microsoft really have the implicit int extension in C++?
666       if (S.getLangOptions().CPlusPlus &&
667           !S.getLangOptions().MicrosoftExt) {
668         S.Diag(DeclLoc, diag::err_missing_type_specifier)
669           << DS.getSourceRange();
670 
671         // When this occurs in C++ code, often something is very broken with the
672         // value being declared, poison it as invalid so we don't get chains of
673         // errors.
674         declarator.setInvalidType(true);
675       } else {
676         S.Diag(DeclLoc, diag::ext_missing_type_specifier)
677           << DS.getSourceRange();
678       }
679     }
680 
681     // FALL THROUGH.
682   case DeclSpec::TST_int: {
683     if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
684       switch (DS.getTypeSpecWidth()) {
685       case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
686       case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
687       case DeclSpec::TSW_long:        Result = Context.LongTy; break;
688       case DeclSpec::TSW_longlong:
689         Result = Context.LongLongTy;
690 
691         // long long is a C99 feature.
692         if (!S.getLangOptions().C99 &&
693             !S.getLangOptions().CPlusPlus0x)
694           S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
695         break;
696       }
697     } else {
698       switch (DS.getTypeSpecWidth()) {
699       case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
700       case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
701       case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
702       case DeclSpec::TSW_longlong:
703         Result = Context.UnsignedLongLongTy;
704 
705         // long long is a C99 feature.
706         if (!S.getLangOptions().C99 &&
707             !S.getLangOptions().CPlusPlus0x)
708           S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
709         break;
710       }
711     }
712     break;
713   }
714   case DeclSpec::TST_float: Result = Context.FloatTy; break;
715   case DeclSpec::TST_double:
716     if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
717       Result = Context.LongDoubleTy;
718     else
719       Result = Context.DoubleTy;
720 
721     if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
722       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
723       declarator.setInvalidType(true);
724     }
725     break;
726   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
727   case DeclSpec::TST_decimal32:    // _Decimal32
728   case DeclSpec::TST_decimal64:    // _Decimal64
729   case DeclSpec::TST_decimal128:   // _Decimal128
730     S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
731     Result = Context.IntTy;
732     declarator.setInvalidType(true);
733     break;
734   case DeclSpec::TST_class:
735   case DeclSpec::TST_enum:
736   case DeclSpec::TST_union:
737   case DeclSpec::TST_struct: {
738     TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
739     if (!D) {
740       // This can happen in C++ with ambiguous lookups.
741       Result = Context.IntTy;
742       declarator.setInvalidType(true);
743       break;
744     }
745 
746     // If the type is deprecated or unavailable, diagnose it.
747     S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
748 
749     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
750            DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
751 
752     // TypeQuals handled by caller.
753     Result = Context.getTypeDeclType(D);
754 
755     // In both C and C++, make an ElaboratedType.
756     ElaboratedTypeKeyword Keyword
757       = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
758     Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
759 
760     if (D->isInvalidDecl())
761       declarator.setInvalidType(true);
762     break;
763   }
764   case DeclSpec::TST_typename: {
765     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
766            DS.getTypeSpecSign() == 0 &&
767            "Can't handle qualifiers on typedef names yet!");
768     Result = S.GetTypeFromParser(DS.getRepAsType());
769     if (Result.isNull())
770       declarator.setInvalidType(true);
771     else if (DeclSpec::ProtocolQualifierListTy PQ
772                = DS.getProtocolQualifiers()) {
773       if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
774         // Silently drop any existing protocol qualifiers.
775         // TODO: determine whether that's the right thing to do.
776         if (ObjT->getNumProtocols())
777           Result = ObjT->getBaseType();
778 
779         if (DS.getNumProtocolQualifiers())
780           Result = Context.getObjCObjectType(Result,
781                                              (ObjCProtocolDecl**) PQ,
782                                              DS.getNumProtocolQualifiers());
783       } else if (Result->isObjCIdType()) {
784         // id<protocol-list>
785         Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
786                                            (ObjCProtocolDecl**) PQ,
787                                            DS.getNumProtocolQualifiers());
788         Result = Context.getObjCObjectPointerType(Result);
789       } else if (Result->isObjCClassType()) {
790         // Class<protocol-list>
791         Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
792                                            (ObjCProtocolDecl**) PQ,
793                                            DS.getNumProtocolQualifiers());
794         Result = Context.getObjCObjectPointerType(Result);
795       } else {
796         S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
797           << DS.getSourceRange();
798         declarator.setInvalidType(true);
799       }
800     }
801 
802     // TypeQuals handled by caller.
803     break;
804   }
805   case DeclSpec::TST_typeofType:
806     // FIXME: Preserve type source info.
807     Result = S.GetTypeFromParser(DS.getRepAsType());
808     assert(!Result.isNull() && "Didn't get a type for typeof?");
809     if (!Result->isDependentType())
810       if (const TagType *TT = Result->getAs<TagType>())
811         S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
812     // TypeQuals handled by caller.
813     Result = Context.getTypeOfType(Result);
814     break;
815   case DeclSpec::TST_typeofExpr: {
816     Expr *E = DS.getRepAsExpr();
817     assert(E && "Didn't get an expression for typeof?");
818     // TypeQuals handled by caller.
819     Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
820     if (Result.isNull()) {
821       Result = Context.IntTy;
822       declarator.setInvalidType(true);
823     }
824     break;
825   }
826   case DeclSpec::TST_decltype: {
827     Expr *E = DS.getRepAsExpr();
828     assert(E && "Didn't get an expression for decltype?");
829     // TypeQuals handled by caller.
830     Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
831     if (Result.isNull()) {
832       Result = Context.IntTy;
833       declarator.setInvalidType(true);
834     }
835     break;
836   }
837   case DeclSpec::TST_underlyingType:
838     Result = S.GetTypeFromParser(DS.getRepAsType());
839     assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
840     Result = S.BuildUnaryTransformType(Result,
841                                        UnaryTransformType::EnumUnderlyingType,
842                                        DS.getTypeSpecTypeLoc());
843     if (Result.isNull()) {
844       Result = Context.IntTy;
845       declarator.setInvalidType(true);
846     }
847     break;
848 
849   case DeclSpec::TST_auto: {
850     // TypeQuals handled by caller.
851     Result = Context.getAutoType(QualType());
852     break;
853   }
854 
855   case DeclSpec::TST_unknown_anytype:
856     Result = Context.UnknownAnyTy;
857     break;
858 
859   case DeclSpec::TST_error:
860     Result = Context.IntTy;
861     declarator.setInvalidType(true);
862     break;
863   }
864 
865   // Handle complex types.
866   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
867     if (S.getLangOptions().Freestanding)
868       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
869     Result = Context.getComplexType(Result);
870   } else if (DS.isTypeAltiVecVector()) {
871     unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
872     assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
873     VectorType::VectorKind VecKind = VectorType::AltiVecVector;
874     if (DS.isTypeAltiVecPixel())
875       VecKind = VectorType::AltiVecPixel;
876     else if (DS.isTypeAltiVecBool())
877       VecKind = VectorType::AltiVecBool;
878     Result = Context.getVectorType(Result, 128/typeSize, VecKind);
879   }
880 
881   // FIXME: Imaginary.
882   if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
883     S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
884 
885   // Before we process any type attributes, synthesize a block literal
886   // function declarator if necessary.
887   if (declarator.getContext() == Declarator::BlockLiteralContext)
888     maybeSynthesizeBlockSignature(state, Result);
889 
890   // Apply any type attributes from the decl spec.  This may cause the
891   // list of type attributes to be temporarily saved while the type
892   // attributes are pushed around.
893   if (AttributeList *attrs = DS.getAttributes().getList())
894     processTypeAttrs(state, Result, true, attrs);
895 
896   // Apply const/volatile/restrict qualifiers to T.
897   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
898 
899     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
900     // or incomplete types shall not be restrict-qualified."  C++ also allows
901     // restrict-qualified references.
902     if (TypeQuals & DeclSpec::TQ_restrict) {
903       if (Result->isAnyPointerType() || Result->isReferenceType()) {
904         QualType EltTy;
905         if (Result->isObjCObjectPointerType())
906           EltTy = Result;
907         else
908           EltTy = Result->isPointerType() ?
909                     Result->getAs<PointerType>()->getPointeeType() :
910                     Result->getAs<ReferenceType>()->getPointeeType();
911 
912         // If we have a pointer or reference, the pointee must have an object
913         // incomplete type.
914         if (!EltTy->isIncompleteOrObjectType()) {
915           S.Diag(DS.getRestrictSpecLoc(),
916                diag::err_typecheck_invalid_restrict_invalid_pointee)
917             << EltTy << DS.getSourceRange();
918           TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
919         }
920       } else {
921         S.Diag(DS.getRestrictSpecLoc(),
922                diag::err_typecheck_invalid_restrict_not_pointer)
923           << Result << DS.getSourceRange();
924         TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
925       }
926     }
927 
928     // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
929     // of a function type includes any type qualifiers, the behavior is
930     // undefined."
931     if (Result->isFunctionType() && TypeQuals) {
932       // Get some location to point at, either the C or V location.
933       SourceLocation Loc;
934       if (TypeQuals & DeclSpec::TQ_const)
935         Loc = DS.getConstSpecLoc();
936       else if (TypeQuals & DeclSpec::TQ_volatile)
937         Loc = DS.getVolatileSpecLoc();
938       else {
939         assert((TypeQuals & DeclSpec::TQ_restrict) &&
940                "Has CVR quals but not C, V, or R?");
941         Loc = DS.getRestrictSpecLoc();
942       }
943       S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
944         << Result << DS.getSourceRange();
945     }
946 
947     // C++ [dcl.ref]p1:
948     //   Cv-qualified references are ill-formed except when the
949     //   cv-qualifiers are introduced through the use of a typedef
950     //   (7.1.3) or of a template type argument (14.3), in which
951     //   case the cv-qualifiers are ignored.
952     // FIXME: Shouldn't we be checking SCS_typedef here?
953     if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
954         TypeQuals && Result->isReferenceType()) {
955       TypeQuals &= ~DeclSpec::TQ_const;
956       TypeQuals &= ~DeclSpec::TQ_volatile;
957     }
958 
959     Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
960     Result = Context.getQualifiedType(Result, Quals);
961   }
962 
963   return Result;
964 }
965 
966 static std::string getPrintableNameForEntity(DeclarationName Entity) {
967   if (Entity)
968     return Entity.getAsString();
969 
970   return "type name";
971 }
972 
973 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
974                                   Qualifiers Qs) {
975   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
976   // object or incomplete types shall not be restrict-qualified."
977   if (Qs.hasRestrict()) {
978     unsigned DiagID = 0;
979     QualType ProblemTy;
980 
981     const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
982     if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
983       if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
984         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
985         ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
986       }
987     } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
988       if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
989         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
990         ProblemTy = T->getAs<PointerType>()->getPointeeType();
991       }
992     } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
993       if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
994         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
995         ProblemTy = T->getAs<PointerType>()->getPointeeType();
996       }
997     } else if (!Ty->isDependentType()) {
998       // FIXME: this deserves a proper diagnostic
999       DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1000       ProblemTy = T;
1001     }
1002 
1003     if (DiagID) {
1004       Diag(Loc, DiagID) << ProblemTy;
1005       Qs.removeRestrict();
1006     }
1007   }
1008 
1009   return Context.getQualifiedType(T, Qs);
1010 }
1011 
1012 /// \brief Build a paren type including \p T.
1013 QualType Sema::BuildParenType(QualType T) {
1014   return Context.getParenType(T);
1015 }
1016 
1017 /// Given that we're building a pointer or reference to the given
1018 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1019                                            SourceLocation loc,
1020                                            bool isReference) {
1021   // Bail out if retention is unrequired or already specified.
1022   if (!type->isObjCLifetimeType() ||
1023       type.getObjCLifetime() != Qualifiers::OCL_None)
1024     return type;
1025 
1026   Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1027 
1028   // If the object type is const-qualified, we can safely use
1029   // __unsafe_unretained.  This is safe (because there are no read
1030   // barriers), and it'll be safe to coerce anything but __weak* to
1031   // the resulting type.
1032   if (type.isConstQualified()) {
1033     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1034 
1035   // Otherwise, check whether the static type does not require
1036   // retaining.  This currently only triggers for Class (possibly
1037   // protocol-qualifed, and arrays thereof).
1038   } else if (type->isObjCARCImplicitlyUnretainedType()) {
1039     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1040 
1041   // If we are in an unevaluated context, like sizeof, assume ExplicitNone and
1042   // don't give error.
1043   } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) {
1044     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1045 
1046   // If that failed, give an error and recover using __autoreleasing.
1047   } else {
1048     // These types can show up in private ivars in system headers, so
1049     // we need this to not be an error in those cases.  Instead we
1050     // want to delay.
1051     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1052       S.DelayedDiagnostics.add(
1053           sema::DelayedDiagnostic::makeForbiddenType(loc,
1054               diag::err_arc_indirect_no_ownership, type, isReference));
1055     } else {
1056       S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1057     }
1058     implicitLifetime = Qualifiers::OCL_Autoreleasing;
1059   }
1060   assert(implicitLifetime && "didn't infer any lifetime!");
1061 
1062   Qualifiers qs;
1063   qs.addObjCLifetime(implicitLifetime);
1064   return S.Context.getQualifiedType(type, qs);
1065 }
1066 
1067 /// \brief Build a pointer type.
1068 ///
1069 /// \param T The type to which we'll be building a pointer.
1070 ///
1071 /// \param Loc The location of the entity whose type involves this
1072 /// pointer type or, if there is no such entity, the location of the
1073 /// type that will have pointer type.
1074 ///
1075 /// \param Entity The name of the entity that involves the pointer
1076 /// type, if known.
1077 ///
1078 /// \returns A suitable pointer type, if there are no
1079 /// errors. Otherwise, returns a NULL type.
1080 QualType Sema::BuildPointerType(QualType T,
1081                                 SourceLocation Loc, DeclarationName Entity) {
1082   if (T->isReferenceType()) {
1083     // C++ 8.3.2p4: There shall be no ... pointers to references ...
1084     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1085       << getPrintableNameForEntity(Entity) << T;
1086     return QualType();
1087   }
1088 
1089   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1090 
1091   // In ARC, it is forbidden to build pointers to unqualified pointers.
1092   if (getLangOptions().ObjCAutoRefCount)
1093     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1094 
1095   // Build the pointer type.
1096   return Context.getPointerType(T);
1097 }
1098 
1099 /// \brief Build a reference type.
1100 ///
1101 /// \param T The type to which we'll be building a reference.
1102 ///
1103 /// \param Loc The location of the entity whose type involves this
1104 /// reference type or, if there is no such entity, the location of the
1105 /// type that will have reference type.
1106 ///
1107 /// \param Entity The name of the entity that involves the reference
1108 /// type, if known.
1109 ///
1110 /// \returns A suitable reference type, if there are no
1111 /// errors. Otherwise, returns a NULL type.
1112 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1113                                   SourceLocation Loc,
1114                                   DeclarationName Entity) {
1115   assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1116          "Unresolved overloaded function type");
1117 
1118   // C++0x [dcl.ref]p6:
1119   //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1120   //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1121   //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1122   //   the type "lvalue reference to T", while an attempt to create the type
1123   //   "rvalue reference to cv TR" creates the type TR.
1124   bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1125 
1126   // C++ [dcl.ref]p4: There shall be no references to references.
1127   //
1128   // According to C++ DR 106, references to references are only
1129   // diagnosed when they are written directly (e.g., "int & &"),
1130   // but not when they happen via a typedef:
1131   //
1132   //   typedef int& intref;
1133   //   typedef intref& intref2;
1134   //
1135   // Parser::ParseDeclaratorInternal diagnoses the case where
1136   // references are written directly; here, we handle the
1137   // collapsing of references-to-references as described in C++0x.
1138   // DR 106 and 540 introduce reference-collapsing into C++98/03.
1139 
1140   // C++ [dcl.ref]p1:
1141   //   A declarator that specifies the type "reference to cv void"
1142   //   is ill-formed.
1143   if (T->isVoidType()) {
1144     Diag(Loc, diag::err_reference_to_void);
1145     return QualType();
1146   }
1147 
1148   // In ARC, it is forbidden to build references to unqualified pointers.
1149   if (getLangOptions().ObjCAutoRefCount)
1150     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1151 
1152   // Handle restrict on references.
1153   if (LValueRef)
1154     return Context.getLValueReferenceType(T, SpelledAsLValue);
1155   return Context.getRValueReferenceType(T);
1156 }
1157 
1158 /// Check whether the specified array size makes the array type a VLA.  If so,
1159 /// return true, if not, return the size of the array in SizeVal.
1160 static bool isArraySizeVLA(Expr *ArraySize, llvm::APSInt &SizeVal, Sema &S) {
1161   // If the size is an ICE, it certainly isn't a VLA.
1162   if (ArraySize->isIntegerConstantExpr(SizeVal, S.Context))
1163     return false;
1164 
1165   // If we're in a GNU mode (like gnu99, but not c99) accept any evaluatable
1166   // value as an extension.
1167   Expr::EvalResult Result;
1168   if (S.LangOpts.GNUMode && ArraySize->Evaluate(Result, S.Context)) {
1169     if (!Result.hasSideEffects() && Result.Val.isInt()) {
1170       SizeVal = Result.Val.getInt();
1171       S.Diag(ArraySize->getLocStart(), diag::ext_vla_folded_to_constant);
1172       return false;
1173     }
1174   }
1175 
1176   return true;
1177 }
1178 
1179 
1180 /// \brief Build an array type.
1181 ///
1182 /// \param T The type of each element in the array.
1183 ///
1184 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1185 ///
1186 /// \param ArraySize Expression describing the size of the array.
1187 ///
1188 /// \param Loc The location of the entity whose type involves this
1189 /// array type or, if there is no such entity, the location of the
1190 /// type that will have array type.
1191 ///
1192 /// \param Entity The name of the entity that involves the array
1193 /// type, if known.
1194 ///
1195 /// \returns A suitable array type, if there are no errors. Otherwise,
1196 /// returns a NULL type.
1197 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1198                               Expr *ArraySize, unsigned Quals,
1199                               SourceRange Brackets, DeclarationName Entity) {
1200 
1201   SourceLocation Loc = Brackets.getBegin();
1202   if (getLangOptions().CPlusPlus) {
1203     // C++ [dcl.array]p1:
1204     //   T is called the array element type; this type shall not be a reference
1205     //   type, the (possibly cv-qualified) type void, a function type or an
1206     //   abstract class type.
1207     //
1208     // Note: function types are handled in the common path with C.
1209     if (T->isReferenceType()) {
1210       Diag(Loc, diag::err_illegal_decl_array_of_references)
1211       << getPrintableNameForEntity(Entity) << T;
1212       return QualType();
1213     }
1214 
1215     if (T->isVoidType()) {
1216       Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1217       return QualType();
1218     }
1219 
1220     if (RequireNonAbstractType(Brackets.getBegin(), T,
1221                                diag::err_array_of_abstract_type))
1222       return QualType();
1223 
1224   } else {
1225     // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1226     // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1227     if (RequireCompleteType(Loc, T,
1228                             diag::err_illegal_decl_array_incomplete_type))
1229       return QualType();
1230   }
1231 
1232   if (T->isFunctionType()) {
1233     Diag(Loc, diag::err_illegal_decl_array_of_functions)
1234       << getPrintableNameForEntity(Entity) << T;
1235     return QualType();
1236   }
1237 
1238   if (T->getContainedAutoType()) {
1239     Diag(Loc, diag::err_illegal_decl_array_of_auto)
1240       << getPrintableNameForEntity(Entity) << T;
1241     return QualType();
1242   }
1243 
1244   if (const RecordType *EltTy = T->getAs<RecordType>()) {
1245     // If the element type is a struct or union that contains a variadic
1246     // array, accept it as a GNU extension: C99 6.7.2.1p2.
1247     if (EltTy->getDecl()->hasFlexibleArrayMember())
1248       Diag(Loc, diag::ext_flexible_array_in_array) << T;
1249   } else if (T->isObjCObjectType()) {
1250     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1251     return QualType();
1252   }
1253 
1254   // Do lvalue-to-rvalue conversions on the array size expression.
1255   if (ArraySize && !ArraySize->isRValue()) {
1256     ExprResult Result = DefaultLvalueConversion(ArraySize);
1257     if (Result.isInvalid())
1258       return QualType();
1259 
1260     ArraySize = Result.take();
1261   }
1262 
1263   // C99 6.7.5.2p1: The size expression shall have integer type.
1264   // TODO: in theory, if we were insane, we could allow contextual
1265   // conversions to integer type here.
1266   if (ArraySize && !ArraySize->isTypeDependent() &&
1267       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1268     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1269       << ArraySize->getType() << ArraySize->getSourceRange();
1270     return QualType();
1271   }
1272   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1273   if (!ArraySize) {
1274     if (ASM == ArrayType::Star)
1275       T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1276     else
1277       T = Context.getIncompleteArrayType(T, ASM, Quals);
1278   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1279     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1280   } else if (!T->isDependentType() && !T->isIncompleteType() &&
1281              !T->isConstantSizeType()) {
1282     // C99: an array with an element type that has a non-constant-size is a VLA.
1283     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1284   } else if (isArraySizeVLA(ArraySize, ConstVal, *this)) {
1285     // C99: an array with a non-ICE size is a VLA.  We accept any expression
1286     // that we can fold to a non-zero positive value as an extension.
1287     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1288   } else {
1289     // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1290     // have a value greater than zero.
1291     if (ConstVal.isSigned() && ConstVal.isNegative()) {
1292       if (Entity)
1293         Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1294           << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1295       else
1296         Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1297           << ArraySize->getSourceRange();
1298       return QualType();
1299     }
1300     if (ConstVal == 0) {
1301       // GCC accepts zero sized static arrays. We allow them when
1302       // we're not in a SFINAE context.
1303       Diag(ArraySize->getLocStart(),
1304            isSFINAEContext()? diag::err_typecheck_zero_array_size
1305                             : diag::ext_typecheck_zero_array_size)
1306         << ArraySize->getSourceRange();
1307     } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1308                !T->isIncompleteType()) {
1309       // Is the array too large?
1310       unsigned ActiveSizeBits
1311         = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1312       if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1313         Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1314           << ConstVal.toString(10)
1315           << ArraySize->getSourceRange();
1316     }
1317 
1318     T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1319   }
1320   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1321   if (!getLangOptions().C99) {
1322     if (T->isVariableArrayType()) {
1323       // Prohibit the use of non-POD types in VLAs.
1324       QualType BaseT = Context.getBaseElementType(T);
1325       if (!T->isDependentType() &&
1326           !BaseT.isPODType(Context) &&
1327           !BaseT->isObjCLifetimeType()) {
1328         Diag(Loc, diag::err_vla_non_pod)
1329           << BaseT;
1330         return QualType();
1331       }
1332       // Prohibit the use of VLAs during template argument deduction.
1333       else if (isSFINAEContext()) {
1334         Diag(Loc, diag::err_vla_in_sfinae);
1335         return QualType();
1336       }
1337       // Just extwarn about VLAs.
1338       else
1339         Diag(Loc, diag::ext_vla);
1340     } else if (ASM != ArrayType::Normal || Quals != 0)
1341       Diag(Loc,
1342            getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1343                                      : diag::ext_c99_array_usage);
1344   }
1345 
1346   return T;
1347 }
1348 
1349 /// \brief Build an ext-vector type.
1350 ///
1351 /// Run the required checks for the extended vector type.
1352 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1353                                   SourceLocation AttrLoc) {
1354   // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1355   // in conjunction with complex types (pointers, arrays, functions, etc.).
1356   if (!T->isDependentType() &&
1357       !T->isIntegerType() && !T->isRealFloatingType()) {
1358     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1359     return QualType();
1360   }
1361 
1362   if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1363     llvm::APSInt vecSize(32);
1364     if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1365       Diag(AttrLoc, diag::err_attribute_argument_not_int)
1366         << "ext_vector_type" << ArraySize->getSourceRange();
1367       return QualType();
1368     }
1369 
1370     // unlike gcc's vector_size attribute, the size is specified as the
1371     // number of elements, not the number of bytes.
1372     unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1373 
1374     if (vectorSize == 0) {
1375       Diag(AttrLoc, diag::err_attribute_zero_size)
1376       << ArraySize->getSourceRange();
1377       return QualType();
1378     }
1379 
1380     return Context.getExtVectorType(T, vectorSize);
1381   }
1382 
1383   return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1384 }
1385 
1386 /// \brief Build a function type.
1387 ///
1388 /// This routine checks the function type according to C++ rules and
1389 /// under the assumption that the result type and parameter types have
1390 /// just been instantiated from a template. It therefore duplicates
1391 /// some of the behavior of GetTypeForDeclarator, but in a much
1392 /// simpler form that is only suitable for this narrow use case.
1393 ///
1394 /// \param T The return type of the function.
1395 ///
1396 /// \param ParamTypes The parameter types of the function. This array
1397 /// will be modified to account for adjustments to the types of the
1398 /// function parameters.
1399 ///
1400 /// \param NumParamTypes The number of parameter types in ParamTypes.
1401 ///
1402 /// \param Variadic Whether this is a variadic function type.
1403 ///
1404 /// \param Quals The cvr-qualifiers to be applied to the function type.
1405 ///
1406 /// \param Loc The location of the entity whose type involves this
1407 /// function type or, if there is no such entity, the location of the
1408 /// type that will have function type.
1409 ///
1410 /// \param Entity The name of the entity that involves the function
1411 /// type, if known.
1412 ///
1413 /// \returns A suitable function type, if there are no
1414 /// errors. Otherwise, returns a NULL type.
1415 QualType Sema::BuildFunctionType(QualType T,
1416                                  QualType *ParamTypes,
1417                                  unsigned NumParamTypes,
1418                                  bool Variadic, unsigned Quals,
1419                                  RefQualifierKind RefQualifier,
1420                                  SourceLocation Loc, DeclarationName Entity,
1421                                  FunctionType::ExtInfo Info) {
1422   if (T->isArrayType() || T->isFunctionType()) {
1423     Diag(Loc, diag::err_func_returning_array_function)
1424       << T->isFunctionType() << T;
1425     return QualType();
1426   }
1427 
1428   bool Invalid = false;
1429   for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
1430     QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1431     if (ParamType->isVoidType()) {
1432       Diag(Loc, diag::err_param_with_void_type);
1433       Invalid = true;
1434     }
1435 
1436     ParamTypes[Idx] = ParamType;
1437   }
1438 
1439   if (Invalid)
1440     return QualType();
1441 
1442   FunctionProtoType::ExtProtoInfo EPI;
1443   EPI.Variadic = Variadic;
1444   EPI.TypeQuals = Quals;
1445   EPI.RefQualifier = RefQualifier;
1446   EPI.ExtInfo = Info;
1447 
1448   return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
1449 }
1450 
1451 /// \brief Build a member pointer type \c T Class::*.
1452 ///
1453 /// \param T the type to which the member pointer refers.
1454 /// \param Class the class type into which the member pointer points.
1455 /// \param CVR Qualifiers applied to the member pointer type
1456 /// \param Loc the location where this type begins
1457 /// \param Entity the name of the entity that will have this member pointer type
1458 ///
1459 /// \returns a member pointer type, if successful, or a NULL type if there was
1460 /// an error.
1461 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1462                                       SourceLocation Loc,
1463                                       DeclarationName Entity) {
1464   // Verify that we're not building a pointer to pointer to function with
1465   // exception specification.
1466   if (CheckDistantExceptionSpec(T)) {
1467     Diag(Loc, diag::err_distant_exception_spec);
1468 
1469     // FIXME: If we're doing this as part of template instantiation,
1470     // we should return immediately.
1471 
1472     // Build the type anyway, but use the canonical type so that the
1473     // exception specifiers are stripped off.
1474     T = Context.getCanonicalType(T);
1475   }
1476 
1477   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1478   //   with reference type, or "cv void."
1479   if (T->isReferenceType()) {
1480     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1481       << (Entity? Entity.getAsString() : "type name") << T;
1482     return QualType();
1483   }
1484 
1485   if (T->isVoidType()) {
1486     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1487       << (Entity? Entity.getAsString() : "type name");
1488     return QualType();
1489   }
1490 
1491   if (!Class->isDependentType() && !Class->isRecordType()) {
1492     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1493     return QualType();
1494   }
1495 
1496   // In the Microsoft ABI, the class is allowed to be an incomplete
1497   // type. In such cases, the compiler makes a worst-case assumption.
1498   // We make no such assumption right now, so emit an error if the
1499   // class isn't a complete type.
1500   if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
1501       RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1502     return QualType();
1503 
1504   return Context.getMemberPointerType(T, Class.getTypePtr());
1505 }
1506 
1507 /// \brief Build a block pointer type.
1508 ///
1509 /// \param T The type to which we'll be building a block pointer.
1510 ///
1511 /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
1512 ///
1513 /// \param Loc The location of the entity whose type involves this
1514 /// block pointer type or, if there is no such entity, the location of the
1515 /// type that will have block pointer type.
1516 ///
1517 /// \param Entity The name of the entity that involves the block pointer
1518 /// type, if known.
1519 ///
1520 /// \returns A suitable block pointer type, if there are no
1521 /// errors. Otherwise, returns a NULL type.
1522 QualType Sema::BuildBlockPointerType(QualType T,
1523                                      SourceLocation Loc,
1524                                      DeclarationName Entity) {
1525   if (!T->isFunctionType()) {
1526     Diag(Loc, diag::err_nonfunction_block_type);
1527     return QualType();
1528   }
1529 
1530   return Context.getBlockPointerType(T);
1531 }
1532 
1533 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1534   QualType QT = Ty.get();
1535   if (QT.isNull()) {
1536     if (TInfo) *TInfo = 0;
1537     return QualType();
1538   }
1539 
1540   TypeSourceInfo *DI = 0;
1541   if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1542     QT = LIT->getType();
1543     DI = LIT->getTypeSourceInfo();
1544   }
1545 
1546   if (TInfo) *TInfo = DI;
1547   return QT;
1548 }
1549 
1550 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1551                                             Qualifiers::ObjCLifetime ownership,
1552                                             unsigned chunkIndex);
1553 
1554 /// Given that this is the declaration of a parameter under ARC,
1555 /// attempt to infer attributes and such for pointer-to-whatever
1556 /// types.
1557 static void inferARCWriteback(TypeProcessingState &state,
1558                               QualType &declSpecType) {
1559   Sema &S = state.getSema();
1560   Declarator &declarator = state.getDeclarator();
1561 
1562   // TODO: should we care about decl qualifiers?
1563 
1564   // Check whether the declarator has the expected form.  We walk
1565   // from the inside out in order to make the block logic work.
1566   unsigned outermostPointerIndex = 0;
1567   bool isBlockPointer = false;
1568   unsigned numPointers = 0;
1569   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1570     unsigned chunkIndex = i;
1571     DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1572     switch (chunk.Kind) {
1573     case DeclaratorChunk::Paren:
1574       // Ignore parens.
1575       break;
1576 
1577     case DeclaratorChunk::Reference:
1578     case DeclaratorChunk::Pointer:
1579       // Count the number of pointers.  Treat references
1580       // interchangeably as pointers; if they're mis-ordered, normal
1581       // type building will discover that.
1582       outermostPointerIndex = chunkIndex;
1583       numPointers++;
1584       break;
1585 
1586     case DeclaratorChunk::BlockPointer:
1587       // If we have a pointer to block pointer, that's an acceptable
1588       // indirect reference; anything else is not an application of
1589       // the rules.
1590       if (numPointers != 1) return;
1591       numPointers++;
1592       outermostPointerIndex = chunkIndex;
1593       isBlockPointer = true;
1594 
1595       // We don't care about pointer structure in return values here.
1596       goto done;
1597 
1598     case DeclaratorChunk::Array: // suppress if written (id[])?
1599     case DeclaratorChunk::Function:
1600     case DeclaratorChunk::MemberPointer:
1601       return;
1602     }
1603   }
1604  done:
1605 
1606   // If we have *one* pointer, then we want to throw the qualifier on
1607   // the declaration-specifiers, which means that it needs to be a
1608   // retainable object type.
1609   if (numPointers == 1) {
1610     // If it's not a retainable object type, the rule doesn't apply.
1611     if (!declSpecType->isObjCRetainableType()) return;
1612 
1613     // If it already has lifetime, don't do anything.
1614     if (declSpecType.getObjCLifetime()) return;
1615 
1616     // Otherwise, modify the type in-place.
1617     Qualifiers qs;
1618 
1619     if (declSpecType->isObjCARCImplicitlyUnretainedType())
1620       qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1621     else
1622       qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1623     declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1624 
1625   // If we have *two* pointers, then we want to throw the qualifier on
1626   // the outermost pointer.
1627   } else if (numPointers == 2) {
1628     // If we don't have a block pointer, we need to check whether the
1629     // declaration-specifiers gave us something that will turn into a
1630     // retainable object pointer after we slap the first pointer on it.
1631     if (!isBlockPointer && !declSpecType->isObjCObjectType())
1632       return;
1633 
1634     // Look for an explicit lifetime attribute there.
1635     DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1636     if (chunk.Kind != DeclaratorChunk::Pointer &&
1637         chunk.Kind != DeclaratorChunk::BlockPointer)
1638       return;
1639     for (const AttributeList *attr = chunk.getAttrs(); attr;
1640            attr = attr->getNext())
1641       if (attr->getKind() == AttributeList::AT_objc_ownership)
1642         return;
1643 
1644     transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1645                                           outermostPointerIndex);
1646 
1647   // Any other number of pointers/references does not trigger the rule.
1648   } else return;
1649 
1650   // TODO: mark whether we did this inference?
1651 }
1652 
1653 static void DiagnoseIgnoredQualifiers(unsigned Quals,
1654                                       SourceLocation ConstQualLoc,
1655                                       SourceLocation VolatileQualLoc,
1656                                       SourceLocation RestrictQualLoc,
1657                                       Sema& S) {
1658   std::string QualStr;
1659   unsigned NumQuals = 0;
1660   SourceLocation Loc;
1661 
1662   FixItHint ConstFixIt;
1663   FixItHint VolatileFixIt;
1664   FixItHint RestrictFixIt;
1665 
1666   const SourceManager &SM = S.getSourceManager();
1667 
1668   // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1669   // find a range and grow it to encompass all the qualifiers, regardless of
1670   // the order in which they textually appear.
1671   if (Quals & Qualifiers::Const) {
1672     ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
1673     QualStr = "const";
1674     ++NumQuals;
1675     if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1676       Loc = ConstQualLoc;
1677   }
1678   if (Quals & Qualifiers::Volatile) {
1679     VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
1680     QualStr += (NumQuals == 0 ? "volatile" : " volatile");
1681     ++NumQuals;
1682     if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1683       Loc = VolatileQualLoc;
1684   }
1685   if (Quals & Qualifiers::Restrict) {
1686     RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
1687     QualStr += (NumQuals == 0 ? "restrict" : " restrict");
1688     ++NumQuals;
1689     if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1690       Loc = RestrictQualLoc;
1691   }
1692 
1693   assert(NumQuals > 0 && "No known qualifiers?");
1694 
1695   S.Diag(Loc, diag::warn_qual_return_type)
1696     << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
1697 }
1698 
1699 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1700                                              TypeSourceInfo *&ReturnTypeInfo) {
1701   Sema &SemaRef = state.getSema();
1702   Declarator &D = state.getDeclarator();
1703   QualType T;
1704   ReturnTypeInfo = 0;
1705 
1706   // The TagDecl owned by the DeclSpec.
1707   TagDecl *OwnedTagDecl = 0;
1708 
1709   switch (D.getName().getKind()) {
1710   case UnqualifiedId::IK_ImplicitSelfParam:
1711   case UnqualifiedId::IK_OperatorFunctionId:
1712   case UnqualifiedId::IK_Identifier:
1713   case UnqualifiedId::IK_LiteralOperatorId:
1714   case UnqualifiedId::IK_TemplateId:
1715     T = ConvertDeclSpecToType(state);
1716 
1717     if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
1718       OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1719       // Owned declaration is embedded in declarator.
1720       OwnedTagDecl->setEmbeddedInDeclarator(true);
1721     }
1722     break;
1723 
1724   case UnqualifiedId::IK_ConstructorName:
1725   case UnqualifiedId::IK_ConstructorTemplateId:
1726   case UnqualifiedId::IK_DestructorName:
1727     // Constructors and destructors don't have return types. Use
1728     // "void" instead.
1729     T = SemaRef.Context.VoidTy;
1730     break;
1731 
1732   case UnqualifiedId::IK_ConversionFunctionId:
1733     // The result type of a conversion function is the type that it
1734     // converts to.
1735     T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
1736                                   &ReturnTypeInfo);
1737     break;
1738   }
1739 
1740   if (D.getAttributes())
1741     distributeTypeAttrsFromDeclarator(state, T);
1742 
1743   // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1744   // In C++0x, a function declarator using 'auto' must have a trailing return
1745   // type (this is checked later) and we can skip this. In other languages
1746   // using auto, we need to check regardless.
1747   if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1748       (!SemaRef.getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
1749     int Error = -1;
1750 
1751     switch (D.getContext()) {
1752     case Declarator::KNRTypeListContext:
1753       llvm_unreachable("K&R type lists aren't allowed in C++");
1754       break;
1755     case Declarator::ObjCParameterContext:
1756     case Declarator::ObjCResultContext:
1757     case Declarator::PrototypeContext:
1758       Error = 0; // Function prototype
1759       break;
1760     case Declarator::MemberContext:
1761       if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1762         break;
1763       switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
1764       case TTK_Enum: llvm_unreachable("unhandled tag kind");
1765       case TTK_Struct: Error = 1; /* Struct member */ break;
1766       case TTK_Union:  Error = 2; /* Union member */ break;
1767       case TTK_Class:  Error = 3; /* Class member */ break;
1768       }
1769       break;
1770     case Declarator::CXXCatchContext:
1771     case Declarator::ObjCCatchContext:
1772       Error = 4; // Exception declaration
1773       break;
1774     case Declarator::TemplateParamContext:
1775       Error = 5; // Template parameter
1776       break;
1777     case Declarator::BlockLiteralContext:
1778       Error = 6; // Block literal
1779       break;
1780     case Declarator::TemplateTypeArgContext:
1781       Error = 7; // Template type argument
1782       break;
1783     case Declarator::AliasDeclContext:
1784     case Declarator::AliasTemplateContext:
1785       Error = 9; // Type alias
1786       break;
1787     case Declarator::TypeNameContext:
1788       Error = 11; // Generic
1789       break;
1790     case Declarator::FileContext:
1791     case Declarator::BlockContext:
1792     case Declarator::ForContext:
1793     case Declarator::ConditionContext:
1794     case Declarator::CXXNewContext:
1795       break;
1796     }
1797 
1798     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1799       Error = 8;
1800 
1801     // In Objective-C it is an error to use 'auto' on a function declarator.
1802     if (D.isFunctionDeclarator())
1803       Error = 10;
1804 
1805     // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1806     // contains a trailing return type. That is only legal at the outermost
1807     // level. Check all declarator chunks (outermost first) anyway, to give
1808     // better diagnostics.
1809     if (SemaRef.getLangOptions().CPlusPlus0x && Error != -1) {
1810       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1811         unsigned chunkIndex = e - i - 1;
1812         state.setCurrentChunkIndex(chunkIndex);
1813         DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1814         if (DeclType.Kind == DeclaratorChunk::Function) {
1815           const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1816           if (FTI.TrailingReturnType) {
1817             Error = -1;
1818             break;
1819           }
1820         }
1821       }
1822     }
1823 
1824     if (Error != -1) {
1825       SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1826                    diag::err_auto_not_allowed)
1827         << Error;
1828       T = SemaRef.Context.IntTy;
1829       D.setInvalidType(true);
1830     }
1831   }
1832 
1833   if (SemaRef.getLangOptions().CPlusPlus &&
1834       OwnedTagDecl && OwnedTagDecl->isDefinition()) {
1835     // Check the contexts where C++ forbids the declaration of a new class
1836     // or enumeration in a type-specifier-seq.
1837     switch (D.getContext()) {
1838     case Declarator::FileContext:
1839     case Declarator::MemberContext:
1840     case Declarator::BlockContext:
1841     case Declarator::ForContext:
1842     case Declarator::BlockLiteralContext:
1843       // C++0x [dcl.type]p3:
1844       //   A type-specifier-seq shall not define a class or enumeration unless
1845       //   it appears in the type-id of an alias-declaration (7.1.3) that is not
1846       //   the declaration of a template-declaration.
1847     case Declarator::AliasDeclContext:
1848       break;
1849     case Declarator::AliasTemplateContext:
1850       SemaRef.Diag(OwnedTagDecl->getLocation(),
1851              diag::err_type_defined_in_alias_template)
1852         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1853       break;
1854     case Declarator::TypeNameContext:
1855     case Declarator::TemplateParamContext:
1856     case Declarator::CXXNewContext:
1857     case Declarator::CXXCatchContext:
1858     case Declarator::ObjCCatchContext:
1859     case Declarator::TemplateTypeArgContext:
1860       SemaRef.Diag(OwnedTagDecl->getLocation(),
1861              diag::err_type_defined_in_type_specifier)
1862         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1863       break;
1864     case Declarator::PrototypeContext:
1865     case Declarator::ObjCParameterContext:
1866     case Declarator::ObjCResultContext:
1867     case Declarator::KNRTypeListContext:
1868       // C++ [dcl.fct]p6:
1869       //   Types shall not be defined in return or parameter types.
1870       SemaRef.Diag(OwnedTagDecl->getLocation(),
1871                    diag::err_type_defined_in_param_type)
1872         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1873       break;
1874     case Declarator::ConditionContext:
1875       // C++ 6.4p2:
1876       // The type-specifier-seq shall not contain typedef and shall not declare
1877       // a new class or enumeration.
1878       SemaRef.Diag(OwnedTagDecl->getLocation(),
1879                    diag::err_type_defined_in_condition);
1880       break;
1881     }
1882   }
1883 
1884   return T;
1885 }
1886 
1887 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
1888                                                 QualType declSpecType,
1889                                                 TypeSourceInfo *TInfo) {
1890 
1891   QualType T = declSpecType;
1892   Declarator &D = state.getDeclarator();
1893   Sema &S = state.getSema();
1894   ASTContext &Context = S.Context;
1895   const LangOptions &LangOpts = S.getLangOptions();
1896 
1897   bool ImplicitlyNoexcept = false;
1898   if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
1899       LangOpts.CPlusPlus0x) {
1900     OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1901     /// In C++0x, deallocation functions (normal and array operator delete)
1902     /// are implicitly noexcept.
1903     if (OO == OO_Delete || OO == OO_Array_Delete)
1904       ImplicitlyNoexcept = true;
1905   }
1906 
1907   // The name we're declaring, if any.
1908   DeclarationName Name;
1909   if (D.getIdentifier())
1910     Name = D.getIdentifier();
1911 
1912   // Does this declaration declare a typedef-name?
1913   bool IsTypedefName =
1914     D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
1915     D.getContext() == Declarator::AliasDeclContext ||
1916     D.getContext() == Declarator::AliasTemplateContext;
1917 
1918   // Walk the DeclTypeInfo, building the recursive type as we go.
1919   // DeclTypeInfos are ordered from the identifier out, which is
1920   // opposite of what we want :).
1921   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1922     unsigned chunkIndex = e - i - 1;
1923     state.setCurrentChunkIndex(chunkIndex);
1924     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1925     switch (DeclType.Kind) {
1926     default: llvm_unreachable("Unknown decltype!");
1927     case DeclaratorChunk::Paren:
1928       T = S.BuildParenType(T);
1929       break;
1930     case DeclaratorChunk::BlockPointer:
1931       // If blocks are disabled, emit an error.
1932       if (!LangOpts.Blocks)
1933         S.Diag(DeclType.Loc, diag::err_blocks_disable);
1934 
1935       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
1936       if (DeclType.Cls.TypeQuals)
1937         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
1938       break;
1939     case DeclaratorChunk::Pointer:
1940       // Verify that we're not building a pointer to pointer to function with
1941       // exception specification.
1942       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1943         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1944         D.setInvalidType(true);
1945         // Build the type anyway.
1946       }
1947       if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
1948         T = Context.getObjCObjectPointerType(T);
1949         if (DeclType.Ptr.TypeQuals)
1950           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1951         break;
1952       }
1953       T = S.BuildPointerType(T, DeclType.Loc, Name);
1954       if (DeclType.Ptr.TypeQuals)
1955         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1956 
1957       break;
1958     case DeclaratorChunk::Reference: {
1959       // Verify that we're not building a reference to pointer to function with
1960       // exception specification.
1961       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1962         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1963         D.setInvalidType(true);
1964         // Build the type anyway.
1965       }
1966       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
1967 
1968       Qualifiers Quals;
1969       if (DeclType.Ref.HasRestrict)
1970         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
1971       break;
1972     }
1973     case DeclaratorChunk::Array: {
1974       // Verify that we're not building an array of pointers to function with
1975       // exception specification.
1976       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1977         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1978         D.setInvalidType(true);
1979         // Build the type anyway.
1980       }
1981       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1982       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1983       ArrayType::ArraySizeModifier ASM;
1984       if (ATI.isStar)
1985         ASM = ArrayType::Star;
1986       else if (ATI.hasStatic)
1987         ASM = ArrayType::Static;
1988       else
1989         ASM = ArrayType::Normal;
1990       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
1991         // FIXME: This check isn't quite right: it allows star in prototypes
1992         // for function definitions, and disallows some edge cases detailed
1993         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1994         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1995         ASM = ArrayType::Normal;
1996         D.setInvalidType(true);
1997       }
1998       T = S.BuildArrayType(T, ASM, ArraySize,
1999                            Qualifiers::fromCVRMask(ATI.TypeQuals),
2000                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2001       break;
2002     }
2003     case DeclaratorChunk::Function: {
2004       // If the function declarator has a prototype (i.e. it is not () and
2005       // does not have a K&R-style identifier list), then the arguments are part
2006       // of the type, otherwise the argument list is ().
2007       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2008 
2009       // Check for auto functions and trailing return type and adjust the
2010       // return type accordingly.
2011       if (!D.isInvalidType()) {
2012         // trailing-return-type is only required if we're declaring a function,
2013         // and not, for instance, a pointer to a function.
2014         if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2015             !FTI.TrailingReturnType && chunkIndex == 0) {
2016           S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2017                diag::err_auto_missing_trailing_return);
2018           T = Context.IntTy;
2019           D.setInvalidType(true);
2020         } else if (FTI.TrailingReturnType) {
2021           // T must be exactly 'auto' at this point. See CWG issue 681.
2022           if (isa<ParenType>(T)) {
2023             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2024                  diag::err_trailing_return_in_parens)
2025               << T << D.getDeclSpec().getSourceRange();
2026             D.setInvalidType(true);
2027           } else if (T.hasQualifiers() || !isa<AutoType>(T)) {
2028             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2029                  diag::err_trailing_return_without_auto)
2030               << T << D.getDeclSpec().getSourceRange();
2031             D.setInvalidType(true);
2032           }
2033 
2034           T = S.GetTypeFromParser(
2035             ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
2036             &TInfo);
2037         }
2038       }
2039 
2040       // C99 6.7.5.3p1: The return type may not be a function or array type.
2041       // For conversion functions, we'll diagnose this particular error later.
2042       if ((T->isArrayType() || T->isFunctionType()) &&
2043           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2044         unsigned diagID = diag::err_func_returning_array_function;
2045         // Last processing chunk in block context means this function chunk
2046         // represents the block.
2047         if (chunkIndex == 0 &&
2048             D.getContext() == Declarator::BlockLiteralContext)
2049           diagID = diag::err_block_returning_array_function;
2050         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2051         T = Context.IntTy;
2052         D.setInvalidType(true);
2053       }
2054 
2055       // cv-qualifiers on return types are pointless except when the type is a
2056       // class type in C++.
2057       if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
2058           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
2059           (!LangOpts.CPlusPlus || !T->isDependentType())) {
2060         assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2061         DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2062         assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2063 
2064         DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2065 
2066         DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2067             SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2068             SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2069             SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2070             S);
2071 
2072       } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
2073           (!LangOpts.CPlusPlus ||
2074            (!T->isDependentType() && !T->isRecordType()))) {
2075 
2076         DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2077                                   D.getDeclSpec().getConstSpecLoc(),
2078                                   D.getDeclSpec().getVolatileSpecLoc(),
2079                                   D.getDeclSpec().getRestrictSpecLoc(),
2080                                   S);
2081       }
2082 
2083       if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
2084         // C++ [dcl.fct]p6:
2085         //   Types shall not be defined in return or parameter types.
2086         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2087         if (Tag->isDefinition())
2088           S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2089             << Context.getTypeDeclType(Tag);
2090       }
2091 
2092       // Exception specs are not allowed in typedefs. Complain, but add it
2093       // anyway.
2094       if (IsTypedefName && FTI.getExceptionSpecType())
2095         S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2096           << (D.getContext() == Declarator::AliasDeclContext ||
2097               D.getContext() == Declarator::AliasTemplateContext);
2098 
2099       if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2100         // Simple void foo(), where the incoming T is the result type.
2101         T = Context.getFunctionNoProtoType(T);
2102       } else {
2103         // We allow a zero-parameter variadic function in C if the
2104         // function is marked with the "overloadable" attribute. Scan
2105         // for this attribute now.
2106         if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
2107           bool Overloadable = false;
2108           for (const AttributeList *Attrs = D.getAttributes();
2109                Attrs; Attrs = Attrs->getNext()) {
2110             if (Attrs->getKind() == AttributeList::AT_overloadable) {
2111               Overloadable = true;
2112               break;
2113             }
2114           }
2115 
2116           if (!Overloadable)
2117             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
2118         }
2119 
2120         if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
2121           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2122           // definition.
2123           S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
2124           D.setInvalidType(true);
2125           break;
2126         }
2127 
2128         FunctionProtoType::ExtProtoInfo EPI;
2129         EPI.Variadic = FTI.isVariadic;
2130         EPI.TypeQuals = FTI.TypeQuals;
2131         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2132                     : FTI.RefQualifierIsLValueRef? RQ_LValue
2133                     : RQ_RValue;
2134 
2135         // Otherwise, we have a function with an argument list that is
2136         // potentially variadic.
2137         SmallVector<QualType, 16> ArgTys;
2138         ArgTys.reserve(FTI.NumArgs);
2139 
2140         SmallVector<bool, 16> ConsumedArguments;
2141         ConsumedArguments.reserve(FTI.NumArgs);
2142         bool HasAnyConsumedArguments = false;
2143 
2144         for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2145           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2146           QualType ArgTy = Param->getType();
2147           assert(!ArgTy.isNull() && "Couldn't parse type?");
2148 
2149           // Adjust the parameter type.
2150           assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2151                  "Unadjusted type?");
2152 
2153           // Look for 'void'.  void is allowed only as a single argument to a
2154           // function with no other parameters (C99 6.7.5.3p10).  We record
2155           // int(void) as a FunctionProtoType with an empty argument list.
2156           if (ArgTy->isVoidType()) {
2157             // If this is something like 'float(int, void)', reject it.  'void'
2158             // is an incomplete type (C99 6.2.5p19) and function decls cannot
2159             // have arguments of incomplete type.
2160             if (FTI.NumArgs != 1 || FTI.isVariadic) {
2161               S.Diag(DeclType.Loc, diag::err_void_only_param);
2162               ArgTy = Context.IntTy;
2163               Param->setType(ArgTy);
2164             } else if (FTI.ArgInfo[i].Ident) {
2165               // Reject, but continue to parse 'int(void abc)'.
2166               S.Diag(FTI.ArgInfo[i].IdentLoc,
2167                    diag::err_param_with_void_type);
2168               ArgTy = Context.IntTy;
2169               Param->setType(ArgTy);
2170             } else {
2171               // Reject, but continue to parse 'float(const void)'.
2172               if (ArgTy.hasQualifiers())
2173                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2174 
2175               // Do not add 'void' to the ArgTys list.
2176               break;
2177             }
2178           } else if (!FTI.hasPrototype) {
2179             if (ArgTy->isPromotableIntegerType()) {
2180               ArgTy = Context.getPromotedIntegerType(ArgTy);
2181               Param->setKNRPromoted(true);
2182             } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
2183               if (BTy->getKind() == BuiltinType::Float) {
2184                 ArgTy = Context.DoubleTy;
2185                 Param->setKNRPromoted(true);
2186               }
2187             }
2188           }
2189 
2190           if (LangOpts.ObjCAutoRefCount) {
2191             bool Consumed = Param->hasAttr<NSConsumedAttr>();
2192             ConsumedArguments.push_back(Consumed);
2193             HasAnyConsumedArguments |= Consumed;
2194           }
2195 
2196           ArgTys.push_back(ArgTy);
2197         }
2198 
2199         if (HasAnyConsumedArguments)
2200           EPI.ConsumedArguments = ConsumedArguments.data();
2201 
2202         SmallVector<QualType, 4> Exceptions;
2203         EPI.ExceptionSpecType = FTI.getExceptionSpecType();
2204         if (FTI.getExceptionSpecType() == EST_Dynamic) {
2205           Exceptions.reserve(FTI.NumExceptions);
2206           for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
2207             // FIXME: Preserve type source info.
2208             QualType ET = S.GetTypeFromParser(FTI.Exceptions[ei].Ty);
2209             // Check that the type is valid for an exception spec, and
2210             // drop it if not.
2211             if (!S.CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
2212               Exceptions.push_back(ET);
2213           }
2214           EPI.NumExceptions = Exceptions.size();
2215           EPI.Exceptions = Exceptions.data();
2216         } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
2217           // If an error occurred, there's no expression here.
2218           if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
2219             assert((NoexceptExpr->isTypeDependent() ||
2220                     NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
2221                         Context.BoolTy) &&
2222                  "Parser should have made sure that the expression is boolean");
2223             SourceLocation ErrLoc;
2224             llvm::APSInt Dummy;
2225             if (!NoexceptExpr->isValueDependent() &&
2226                 !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
2227                                                      /*evaluated*/false))
2228               S.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
2229                   << NoexceptExpr->getSourceRange();
2230             else
2231               EPI.NoexceptExpr = NoexceptExpr;
2232           }
2233         } else if (FTI.getExceptionSpecType() == EST_None &&
2234                    ImplicitlyNoexcept && chunkIndex == 0) {
2235           // Only the outermost chunk is marked noexcept, of course.
2236           EPI.ExceptionSpecType = EST_BasicNoexcept;
2237         }
2238 
2239         T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
2240       }
2241 
2242       break;
2243     }
2244     case DeclaratorChunk::MemberPointer:
2245       // The scope spec must refer to a class, or be dependent.
2246       CXXScopeSpec &SS = DeclType.Mem.Scope();
2247       QualType ClsType;
2248       if (SS.isInvalid()) {
2249         // Avoid emitting extra errors if we already errored on the scope.
2250         D.setInvalidType(true);
2251       } else if (S.isDependentScopeSpecifier(SS) ||
2252                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
2253         NestedNameSpecifier *NNS
2254           = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2255         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2256         switch (NNS->getKind()) {
2257         case NestedNameSpecifier::Identifier:
2258           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
2259                                                  NNS->getAsIdentifier());
2260           break;
2261 
2262         case NestedNameSpecifier::Namespace:
2263         case NestedNameSpecifier::NamespaceAlias:
2264         case NestedNameSpecifier::Global:
2265           llvm_unreachable("Nested-name-specifier must name a type");
2266           break;
2267 
2268         case NestedNameSpecifier::TypeSpec:
2269         case NestedNameSpecifier::TypeSpecWithTemplate:
2270           ClsType = QualType(NNS->getAsType(), 0);
2271           // Note: if the NNS has a prefix and ClsType is a nondependent
2272           // TemplateSpecializationType, then the NNS prefix is NOT included
2273           // in ClsType; hence we wrap ClsType into an ElaboratedType.
2274           // NOTE: in particular, no wrap occurs if ClsType already is an
2275           // Elaborated, DependentName, or DependentTemplateSpecialization.
2276           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
2277             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
2278           break;
2279         }
2280       } else {
2281         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
2282              diag::err_illegal_decl_mempointer_in_nonclass)
2283           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2284           << DeclType.Mem.Scope().getRange();
2285         D.setInvalidType(true);
2286       }
2287 
2288       if (!ClsType.isNull())
2289         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
2290       if (T.isNull()) {
2291         T = Context.IntTy;
2292         D.setInvalidType(true);
2293       } else if (DeclType.Mem.TypeQuals) {
2294         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
2295       }
2296       break;
2297     }
2298 
2299     if (T.isNull()) {
2300       D.setInvalidType(true);
2301       T = Context.IntTy;
2302     }
2303 
2304     // See if there are any attributes on this declarator chunk.
2305     if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2306       processTypeAttrs(state, T, false, attrs);
2307   }
2308 
2309   if (LangOpts.CPlusPlus && T->isFunctionType()) {
2310     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
2311     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
2312 
2313     // C++ 8.3.5p4:
2314     //   A cv-qualifier-seq shall only be part of the function type
2315     //   for a nonstatic member function, the function type to which a pointer
2316     //   to member refers, or the top-level function type of a function typedef
2317     //   declaration.
2318     //
2319     // Core issue 547 also allows cv-qualifiers on function types that are
2320     // top-level template type arguments.
2321     bool FreeFunction;
2322     if (!D.getCXXScopeSpec().isSet()) {
2323       FreeFunction = (D.getContext() != Declarator::MemberContext ||
2324                       D.getDeclSpec().isFriendSpecified());
2325     } else {
2326       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
2327       FreeFunction = (DC && !DC->isRecord());
2328     }
2329 
2330     // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
2331     // function that is not a constructor declares that function to be const.
2332     if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
2333         D.getName().getKind() != UnqualifiedId::IK_ConstructorName &&
2334         D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId &&
2335         !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
2336       // Rebuild function type adding a 'const' qualifier.
2337       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2338       EPI.TypeQuals |= DeclSpec::TQ_const;
2339       T = Context.getFunctionType(FnTy->getResultType(),
2340                                   FnTy->arg_type_begin(),
2341                                   FnTy->getNumArgs(), EPI);
2342     }
2343 
2344     // C++0x [dcl.fct]p6:
2345     //   A ref-qualifier shall only be part of the function type for a
2346     //   non-static member function, the function type to which a pointer to
2347     //   member refers, or the top-level function type of a function typedef
2348     //   declaration.
2349     if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
2350         !(D.getContext() == Declarator::TemplateTypeArgContext &&
2351           !D.isFunctionDeclarator()) && !IsTypedefName &&
2352         (FreeFunction ||
2353          D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
2354       if (D.getContext() == Declarator::TemplateTypeArgContext) {
2355         // Accept qualified function types as template type arguments as a GNU
2356         // extension. This is also the subject of C++ core issue 547.
2357         std::string Quals;
2358         if (FnTy->getTypeQuals() != 0)
2359           Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2360 
2361         switch (FnTy->getRefQualifier()) {
2362         case RQ_None:
2363           break;
2364 
2365         case RQ_LValue:
2366           if (!Quals.empty())
2367             Quals += ' ';
2368           Quals += '&';
2369           break;
2370 
2371         case RQ_RValue:
2372           if (!Quals.empty())
2373             Quals += ' ';
2374           Quals += "&&";
2375           break;
2376         }
2377 
2378         S.Diag(D.getIdentifierLoc(),
2379              diag::ext_qualified_function_type_template_arg)
2380           << Quals;
2381       } else {
2382         if (FnTy->getTypeQuals() != 0) {
2383           if (D.isFunctionDeclarator())
2384             S.Diag(D.getIdentifierLoc(),
2385                  diag::err_invalid_qualified_function_type);
2386           else
2387             S.Diag(D.getIdentifierLoc(),
2388                  diag::err_invalid_qualified_typedef_function_type_use)
2389               << FreeFunction;
2390         }
2391 
2392         if (FnTy->getRefQualifier()) {
2393           if (D.isFunctionDeclarator()) {
2394             SourceLocation Loc = D.getIdentifierLoc();
2395             for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2396               const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2397               if (Chunk.Kind == DeclaratorChunk::Function &&
2398                   Chunk.Fun.hasRefQualifier()) {
2399                 Loc = Chunk.Fun.getRefQualifierLoc();
2400                 break;
2401               }
2402             }
2403 
2404             S.Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
2405               << (FnTy->getRefQualifier() == RQ_LValue)
2406               << FixItHint::CreateRemoval(Loc);
2407           } else {
2408             S.Diag(D.getIdentifierLoc(),
2409                  diag::err_invalid_ref_qualifier_typedef_function_type_use)
2410               << FreeFunction
2411               << (FnTy->getRefQualifier() == RQ_LValue);
2412           }
2413         }
2414 
2415         // Strip the cv-qualifiers and ref-qualifiers from the type.
2416         FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2417         EPI.TypeQuals = 0;
2418         EPI.RefQualifier = RQ_None;
2419 
2420         T = Context.getFunctionType(FnTy->getResultType(),
2421                                     FnTy->arg_type_begin(),
2422                                     FnTy->getNumArgs(), EPI);
2423       }
2424     }
2425   }
2426 
2427   // Apply any undistributed attributes from the declarator.
2428   if (!T.isNull())
2429     if (AttributeList *attrs = D.getAttributes())
2430       processTypeAttrs(state, T, false, attrs);
2431 
2432   // Diagnose any ignored type attributes.
2433   if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2434 
2435   // C++0x [dcl.constexpr]p9:
2436   //  A constexpr specifier used in an object declaration declares the object
2437   //  as const.
2438   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
2439     T.addConst();
2440   }
2441 
2442   // If there was an ellipsis in the declarator, the declaration declares a
2443   // parameter pack whose type may be a pack expansion type.
2444   if (D.hasEllipsis() && !T.isNull()) {
2445     // C++0x [dcl.fct]p13:
2446     //   A declarator-id or abstract-declarator containing an ellipsis shall
2447     //   only be used in a parameter-declaration. Such a parameter-declaration
2448     //   is a parameter pack (14.5.3). [...]
2449     switch (D.getContext()) {
2450     case Declarator::PrototypeContext:
2451       // C++0x [dcl.fct]p13:
2452       //   [...] When it is part of a parameter-declaration-clause, the
2453       //   parameter pack is a function parameter pack (14.5.3). The type T
2454       //   of the declarator-id of the function parameter pack shall contain
2455       //   a template parameter pack; each template parameter pack in T is
2456       //   expanded by the function parameter pack.
2457       //
2458       // We represent function parameter packs as function parameters whose
2459       // type is a pack expansion.
2460       if (!T->containsUnexpandedParameterPack()) {
2461         S.Diag(D.getEllipsisLoc(),
2462              diag::err_function_parameter_pack_without_parameter_packs)
2463           << T <<  D.getSourceRange();
2464         D.setEllipsisLoc(SourceLocation());
2465       } else {
2466         T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2467       }
2468       break;
2469 
2470     case Declarator::TemplateParamContext:
2471       // C++0x [temp.param]p15:
2472       //   If a template-parameter is a [...] is a parameter-declaration that
2473       //   declares a parameter pack (8.3.5), then the template-parameter is a
2474       //   template parameter pack (14.5.3).
2475       //
2476       // Note: core issue 778 clarifies that, if there are any unexpanded
2477       // parameter packs in the type of the non-type template parameter, then
2478       // it expands those parameter packs.
2479       if (T->containsUnexpandedParameterPack())
2480         T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2481       else if (!LangOpts.CPlusPlus0x)
2482         S.Diag(D.getEllipsisLoc(), diag::ext_variadic_templates);
2483       break;
2484 
2485     case Declarator::FileContext:
2486     case Declarator::KNRTypeListContext:
2487     case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
2488     case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
2489     case Declarator::TypeNameContext:
2490     case Declarator::CXXNewContext:
2491     case Declarator::AliasDeclContext:
2492     case Declarator::AliasTemplateContext:
2493     case Declarator::MemberContext:
2494     case Declarator::BlockContext:
2495     case Declarator::ForContext:
2496     case Declarator::ConditionContext:
2497     case Declarator::CXXCatchContext:
2498     case Declarator::ObjCCatchContext:
2499     case Declarator::BlockLiteralContext:
2500     case Declarator::TemplateTypeArgContext:
2501       // FIXME: We may want to allow parameter packs in block-literal contexts
2502       // in the future.
2503       S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
2504       D.setEllipsisLoc(SourceLocation());
2505       break;
2506     }
2507   }
2508 
2509   if (T.isNull())
2510     return Context.getNullTypeSourceInfo();
2511   else if (D.isInvalidType())
2512     return Context.getTrivialTypeSourceInfo(T);
2513 
2514   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2515 }
2516 
2517 /// GetTypeForDeclarator - Convert the type for the specified
2518 /// declarator to Type instances.
2519 ///
2520 /// The result of this call will never be null, but the associated
2521 /// type may be a null type if there's an unrecoverable error.
2522 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2523   // Determine the type of the declarator. Not all forms of declarator
2524   // have a type.
2525 
2526   TypeProcessingState state(*this, D);
2527 
2528   TypeSourceInfo *ReturnTypeInfo = 0;
2529   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2530   if (T.isNull())
2531     return Context.getNullTypeSourceInfo();
2532 
2533   if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount)
2534     inferARCWriteback(state, T);
2535 
2536   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
2537 }
2538 
2539 static void transferARCOwnershipToDeclSpec(Sema &S,
2540                                            QualType &declSpecTy,
2541                                            Qualifiers::ObjCLifetime ownership) {
2542   if (declSpecTy->isObjCRetainableType() &&
2543       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2544     Qualifiers qs;
2545     qs.addObjCLifetime(ownership);
2546     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2547   }
2548 }
2549 
2550 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2551                                             Qualifiers::ObjCLifetime ownership,
2552                                             unsigned chunkIndex) {
2553   Sema &S = state.getSema();
2554   Declarator &D = state.getDeclarator();
2555 
2556   // Look for an explicit lifetime attribute.
2557   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2558   for (const AttributeList *attr = chunk.getAttrs(); attr;
2559          attr = attr->getNext())
2560     if (attr->getKind() == AttributeList::AT_objc_ownership)
2561       return;
2562 
2563   const char *attrStr = 0;
2564   switch (ownership) {
2565   case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
2566   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2567   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2568   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2569   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2570   }
2571 
2572   // If there wasn't one, add one (with an invalid source location
2573   // so that we don't make an AttributedType for it).
2574   AttributeList *attr = D.getAttributePool()
2575     .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2576             /*scope*/ 0, SourceLocation(),
2577             &S.Context.Idents.get(attrStr), SourceLocation(),
2578             /*args*/ 0, 0,
2579             /*declspec*/ false, /*C++0x*/ false);
2580   spliceAttrIntoList(*attr, chunk.getAttrListRef());
2581 
2582   // TODO: mark whether we did this inference?
2583 }
2584 
2585 static void transferARCOwnership(TypeProcessingState &state,
2586                                  QualType &declSpecTy,
2587                                  Qualifiers::ObjCLifetime ownership) {
2588   Sema &S = state.getSema();
2589   Declarator &D = state.getDeclarator();
2590 
2591   int inner = -1;
2592   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2593     DeclaratorChunk &chunk = D.getTypeObject(i);
2594     switch (chunk.Kind) {
2595     case DeclaratorChunk::Paren:
2596       // Ignore parens.
2597       break;
2598 
2599     case DeclaratorChunk::Array:
2600     case DeclaratorChunk::Reference:
2601     case DeclaratorChunk::Pointer:
2602       inner = i;
2603       break;
2604 
2605     case DeclaratorChunk::BlockPointer:
2606       return transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2607 
2608     case DeclaratorChunk::Function:
2609     case DeclaratorChunk::MemberPointer:
2610       return;
2611     }
2612   }
2613 
2614   if (inner == -1)
2615     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2616 
2617   DeclaratorChunk &chunk = D.getTypeObject(inner);
2618   if (chunk.Kind == DeclaratorChunk::Pointer) {
2619     if (declSpecTy->isObjCRetainableType())
2620       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2621     if (declSpecTy->isObjCObjectType())
2622       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2623   } else {
2624     assert(chunk.Kind == DeclaratorChunk::Array ||
2625            chunk.Kind == DeclaratorChunk::Reference);
2626     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2627   }
2628 }
2629 
2630 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2631   TypeProcessingState state(*this, D);
2632 
2633   TypeSourceInfo *ReturnTypeInfo = 0;
2634   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2635   if (declSpecTy.isNull())
2636     return Context.getNullTypeSourceInfo();
2637 
2638   if (getLangOptions().ObjCAutoRefCount) {
2639     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
2640     if (ownership != Qualifiers::OCL_None)
2641       transferARCOwnership(state, declSpecTy, ownership);
2642   }
2643 
2644   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
2645 }
2646 
2647 /// Map an AttributedType::Kind to an AttributeList::Kind.
2648 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2649   switch (kind) {
2650   case AttributedType::attr_address_space:
2651     return AttributeList::AT_address_space;
2652   case AttributedType::attr_regparm:
2653     return AttributeList::AT_regparm;
2654   case AttributedType::attr_vector_size:
2655     return AttributeList::AT_vector_size;
2656   case AttributedType::attr_neon_vector_type:
2657     return AttributeList::AT_neon_vector_type;
2658   case AttributedType::attr_neon_polyvector_type:
2659     return AttributeList::AT_neon_polyvector_type;
2660   case AttributedType::attr_objc_gc:
2661     return AttributeList::AT_objc_gc;
2662   case AttributedType::attr_objc_ownership:
2663     return AttributeList::AT_objc_ownership;
2664   case AttributedType::attr_noreturn:
2665     return AttributeList::AT_noreturn;
2666   case AttributedType::attr_cdecl:
2667     return AttributeList::AT_cdecl;
2668   case AttributedType::attr_fastcall:
2669     return AttributeList::AT_fastcall;
2670   case AttributedType::attr_stdcall:
2671     return AttributeList::AT_stdcall;
2672   case AttributedType::attr_thiscall:
2673     return AttributeList::AT_thiscall;
2674   case AttributedType::attr_pascal:
2675     return AttributeList::AT_pascal;
2676   case AttributedType::attr_pcs:
2677     return AttributeList::AT_pcs;
2678   }
2679   llvm_unreachable("unexpected attribute kind!");
2680   return AttributeList::Kind();
2681 }
2682 
2683 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2684                                   const AttributeList *attrs) {
2685   AttributedType::Kind kind = TL.getAttrKind();
2686 
2687   assert(attrs && "no type attributes in the expected location!");
2688   AttributeList::Kind parsedKind = getAttrListKind(kind);
2689   while (attrs->getKind() != parsedKind) {
2690     attrs = attrs->getNext();
2691     assert(attrs && "no matching attribute in expected location!");
2692   }
2693 
2694   TL.setAttrNameLoc(attrs->getLoc());
2695   if (TL.hasAttrExprOperand())
2696     TL.setAttrExprOperand(attrs->getArg(0));
2697   else if (TL.hasAttrEnumOperand())
2698     TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2699 
2700   // FIXME: preserve this information to here.
2701   if (TL.hasAttrOperand())
2702     TL.setAttrOperandParensRange(SourceRange());
2703 }
2704 
2705 namespace {
2706   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
2707     ASTContext &Context;
2708     const DeclSpec &DS;
2709 
2710   public:
2711     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2712       : Context(Context), DS(DS) {}
2713 
2714     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2715       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2716       Visit(TL.getModifiedLoc());
2717     }
2718     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2719       Visit(TL.getUnqualifiedLoc());
2720     }
2721     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2722       TL.setNameLoc(DS.getTypeSpecTypeLoc());
2723     }
2724     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2725       TL.setNameLoc(DS.getTypeSpecTypeLoc());
2726     }
2727     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2728       // Handle the base type, which might not have been written explicitly.
2729       if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2730         TL.setHasBaseTypeAsWritten(false);
2731         TL.getBaseLoc().initialize(Context, SourceLocation());
2732       } else {
2733         TL.setHasBaseTypeAsWritten(true);
2734         Visit(TL.getBaseLoc());
2735       }
2736 
2737       // Protocol qualifiers.
2738       if (DS.getProtocolQualifiers()) {
2739         assert(TL.getNumProtocols() > 0);
2740         assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2741         TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2742         TL.setRAngleLoc(DS.getSourceRange().getEnd());
2743         for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2744           TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2745       } else {
2746         assert(TL.getNumProtocols() == 0);
2747         TL.setLAngleLoc(SourceLocation());
2748         TL.setRAngleLoc(SourceLocation());
2749       }
2750     }
2751     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2752       TL.setStarLoc(SourceLocation());
2753       Visit(TL.getPointeeLoc());
2754     }
2755     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
2756       TypeSourceInfo *TInfo = 0;
2757       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2758 
2759       // If we got no declarator info from previous Sema routines,
2760       // just fill with the typespec loc.
2761       if (!TInfo) {
2762         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
2763         return;
2764       }
2765 
2766       TypeLoc OldTL = TInfo->getTypeLoc();
2767       if (TInfo->getType()->getAs<ElaboratedType>()) {
2768         ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2769         TemplateSpecializationTypeLoc NamedTL =
2770           cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2771         TL.copy(NamedTL);
2772       }
2773       else
2774         TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
2775     }
2776     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2777       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2778       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2779       TL.setParensRange(DS.getTypeofParensRange());
2780     }
2781     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2782       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2783       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2784       TL.setParensRange(DS.getTypeofParensRange());
2785       assert(DS.getRepAsType());
2786       TypeSourceInfo *TInfo = 0;
2787       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2788       TL.setUnderlyingTInfo(TInfo);
2789     }
2790     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2791       // FIXME: This holds only because we only have one unary transform.
2792       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2793       TL.setKWLoc(DS.getTypeSpecTypeLoc());
2794       TL.setParensRange(DS.getTypeofParensRange());
2795       assert(DS.getRepAsType());
2796       TypeSourceInfo *TInfo = 0;
2797       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2798       TL.setUnderlyingTInfo(TInfo);
2799     }
2800     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2801       // By default, use the source location of the type specifier.
2802       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2803       if (TL.needsExtraLocalData()) {
2804         // Set info for the written builtin specifiers.
2805         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2806         // Try to have a meaningful source location.
2807         if (TL.getWrittenSignSpec() != TSS_unspecified)
2808           // Sign spec loc overrides the others (e.g., 'unsigned long').
2809           TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2810         else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2811           // Width spec loc overrides type spec loc (e.g., 'short int').
2812           TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2813       }
2814     }
2815     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2816       ElaboratedTypeKeyword Keyword
2817         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2818       if (DS.getTypeSpecType() == TST_typename) {
2819         TypeSourceInfo *TInfo = 0;
2820         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2821         if (TInfo) {
2822           TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2823           return;
2824         }
2825       }
2826       TL.setKeywordLoc(Keyword != ETK_None
2827                        ? DS.getTypeSpecTypeLoc()
2828                        : SourceLocation());
2829       const CXXScopeSpec& SS = DS.getTypeSpecScope();
2830       TL.setQualifierLoc(SS.getWithLocInContext(Context));
2831       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2832     }
2833     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2834       ElaboratedTypeKeyword Keyword
2835         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2836       if (DS.getTypeSpecType() == TST_typename) {
2837         TypeSourceInfo *TInfo = 0;
2838         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2839         if (TInfo) {
2840           TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2841           return;
2842         }
2843       }
2844       TL.setKeywordLoc(Keyword != ETK_None
2845                        ? DS.getTypeSpecTypeLoc()
2846                        : SourceLocation());
2847       const CXXScopeSpec& SS = DS.getTypeSpecScope();
2848       TL.setQualifierLoc(SS.getWithLocInContext(Context));
2849       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2850     }
2851     void VisitDependentTemplateSpecializationTypeLoc(
2852                                  DependentTemplateSpecializationTypeLoc TL) {
2853       ElaboratedTypeKeyword Keyword
2854         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2855       if (Keyword == ETK_Typename) {
2856         TypeSourceInfo *TInfo = 0;
2857         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2858         if (TInfo) {
2859           TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2860                     TInfo->getTypeLoc()));
2861           return;
2862         }
2863       }
2864       TL.initializeLocal(Context, SourceLocation());
2865       TL.setKeywordLoc(Keyword != ETK_None
2866                        ? DS.getTypeSpecTypeLoc()
2867                        : SourceLocation());
2868       const CXXScopeSpec& SS = DS.getTypeSpecScope();
2869       TL.setQualifierLoc(SS.getWithLocInContext(Context));
2870       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2871     }
2872     void VisitTagTypeLoc(TagTypeLoc TL) {
2873       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2874     }
2875 
2876     void VisitTypeLoc(TypeLoc TL) {
2877       // FIXME: add other typespec types and change this to an assert.
2878       TL.initialize(Context, DS.getTypeSpecTypeLoc());
2879     }
2880   };
2881 
2882   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
2883     ASTContext &Context;
2884     const DeclaratorChunk &Chunk;
2885 
2886   public:
2887     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2888       : Context(Context), Chunk(Chunk) {}
2889 
2890     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2891       llvm_unreachable("qualified type locs not expected here!");
2892     }
2893 
2894     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2895       fillAttributedTypeLoc(TL, Chunk.getAttrs());
2896     }
2897     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2898       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2899       TL.setCaretLoc(Chunk.Loc);
2900     }
2901     void VisitPointerTypeLoc(PointerTypeLoc TL) {
2902       assert(Chunk.Kind == DeclaratorChunk::Pointer);
2903       TL.setStarLoc(Chunk.Loc);
2904     }
2905     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2906       assert(Chunk.Kind == DeclaratorChunk::Pointer);
2907       TL.setStarLoc(Chunk.Loc);
2908     }
2909     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2910       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
2911       const CXXScopeSpec& SS = Chunk.Mem.Scope();
2912       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
2913 
2914       const Type* ClsTy = TL.getClass();
2915       QualType ClsQT = QualType(ClsTy, 0);
2916       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
2917       // Now copy source location info into the type loc component.
2918       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
2919       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
2920       case NestedNameSpecifier::Identifier:
2921         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
2922         {
2923           DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
2924           DNTLoc.setKeywordLoc(SourceLocation());
2925           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
2926           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
2927         }
2928         break;
2929 
2930       case NestedNameSpecifier::TypeSpec:
2931       case NestedNameSpecifier::TypeSpecWithTemplate:
2932         if (isa<ElaboratedType>(ClsTy)) {
2933           ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
2934           ETLoc.setKeywordLoc(SourceLocation());
2935           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
2936           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
2937           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
2938         } else {
2939           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
2940         }
2941         break;
2942 
2943       case NestedNameSpecifier::Namespace:
2944       case NestedNameSpecifier::NamespaceAlias:
2945       case NestedNameSpecifier::Global:
2946         llvm_unreachable("Nested-name-specifier must name a type");
2947         break;
2948       }
2949 
2950       // Finally fill in MemberPointerLocInfo fields.
2951       TL.setStarLoc(Chunk.Loc);
2952       TL.setClassTInfo(ClsTInfo);
2953     }
2954     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2955       assert(Chunk.Kind == DeclaratorChunk::Reference);
2956       // 'Amp' is misleading: this might have been originally
2957       /// spelled with AmpAmp.
2958       TL.setAmpLoc(Chunk.Loc);
2959     }
2960     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2961       assert(Chunk.Kind == DeclaratorChunk::Reference);
2962       assert(!Chunk.Ref.LValueRef);
2963       TL.setAmpAmpLoc(Chunk.Loc);
2964     }
2965     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
2966       assert(Chunk.Kind == DeclaratorChunk::Array);
2967       TL.setLBracketLoc(Chunk.Loc);
2968       TL.setRBracketLoc(Chunk.EndLoc);
2969       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
2970     }
2971     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2972       assert(Chunk.Kind == DeclaratorChunk::Function);
2973       TL.setLocalRangeBegin(Chunk.Loc);
2974       TL.setLocalRangeEnd(Chunk.EndLoc);
2975       TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
2976 
2977       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
2978       for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
2979         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2980         TL.setArg(tpi++, Param);
2981       }
2982       // FIXME: exception specs
2983     }
2984     void VisitParenTypeLoc(ParenTypeLoc TL) {
2985       assert(Chunk.Kind == DeclaratorChunk::Paren);
2986       TL.setLParenLoc(Chunk.Loc);
2987       TL.setRParenLoc(Chunk.EndLoc);
2988     }
2989 
2990     void VisitTypeLoc(TypeLoc TL) {
2991       llvm_unreachable("unsupported TypeLoc kind in declarator!");
2992     }
2993   };
2994 }
2995 
2996 /// \brief Create and instantiate a TypeSourceInfo with type source information.
2997 ///
2998 /// \param T QualType referring to the type as written in source code.
2999 ///
3000 /// \param ReturnTypeInfo For declarators whose return type does not show
3001 /// up in the normal place in the declaration specifiers (such as a C++
3002 /// conversion function), this pointer will refer to a type source information
3003 /// for that return type.
3004 TypeSourceInfo *
3005 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3006                                      TypeSourceInfo *ReturnTypeInfo) {
3007   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3008   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3009 
3010   // Handle parameter packs whose type is a pack expansion.
3011   if (isa<PackExpansionType>(T)) {
3012     cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
3013     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3014   }
3015 
3016   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3017     while (isa<AttributedTypeLoc>(CurrTL)) {
3018       AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3019       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3020       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3021     }
3022 
3023     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3024     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3025   }
3026 
3027   // If we have different source information for the return type, use
3028   // that.  This really only applies to C++ conversion functions.
3029   if (ReturnTypeInfo) {
3030     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3031     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3032     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3033   } else {
3034     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3035   }
3036 
3037   return TInfo;
3038 }
3039 
3040 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
3041 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3042   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3043   // and Sema during declaration parsing. Try deallocating/caching them when
3044   // it's appropriate, instead of allocating them and keeping them around.
3045   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3046                                                        TypeAlignment);
3047   new (LocT) LocInfoType(T, TInfo);
3048   assert(LocT->getTypeClass() != T->getTypeClass() &&
3049          "LocInfoType's TypeClass conflicts with an existing Type class");
3050   return ParsedType::make(QualType(LocT, 0));
3051 }
3052 
3053 void LocInfoType::getAsStringInternal(std::string &Str,
3054                                       const PrintingPolicy &Policy) const {
3055   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3056          " was used directly instead of getting the QualType through"
3057          " GetTypeFromParser");
3058 }
3059 
3060 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3061   // C99 6.7.6: Type names have no identifier.  This is already validated by
3062   // the parser.
3063   assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
3064 
3065   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3066   QualType T = TInfo->getType();
3067   if (D.isInvalidType())
3068     return true;
3069 
3070   // Make sure there are no unused decl attributes on the declarator.
3071   // We don't want to do this for ObjC parameters because we're going
3072   // to apply them to the actual parameter declaration.
3073   if (D.getContext() != Declarator::ObjCParameterContext)
3074     checkUnusedDeclAttributes(D);
3075 
3076   if (getLangOptions().CPlusPlus) {
3077     // Check that there are no default arguments (C++ only).
3078     CheckExtraCXXDefaultArguments(D);
3079   }
3080 
3081   return CreateParsedType(T, TInfo);
3082 }
3083 
3084 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3085   QualType T = Context.getObjCInstanceType();
3086   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3087   return CreateParsedType(T, TInfo);
3088 }
3089 
3090 
3091 //===----------------------------------------------------------------------===//
3092 // Type Attribute Processing
3093 //===----------------------------------------------------------------------===//
3094 
3095 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3096 /// specified type.  The attribute contains 1 argument, the id of the address
3097 /// space for the type.
3098 static void HandleAddressSpaceTypeAttribute(QualType &Type,
3099                                             const AttributeList &Attr, Sema &S){
3100 
3101   // If this type is already address space qualified, reject it.
3102   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3103   // qualifiers for two or more different address spaces."
3104   if (Type.getAddressSpace()) {
3105     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3106     Attr.setInvalid();
3107     return;
3108   }
3109 
3110   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3111   // qualified by an address-space qualifier."
3112   if (Type->isFunctionType()) {
3113     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3114     Attr.setInvalid();
3115     return;
3116   }
3117 
3118   // Check the attribute arguments.
3119   if (Attr.getNumArgs() != 1) {
3120     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3121     Attr.setInvalid();
3122     return;
3123   }
3124   Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3125   llvm::APSInt addrSpace(32);
3126   if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3127       !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3128     S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3129       << ASArgExpr->getSourceRange();
3130     Attr.setInvalid();
3131     return;
3132   }
3133 
3134   // Bounds checking.
3135   if (addrSpace.isSigned()) {
3136     if (addrSpace.isNegative()) {
3137       S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3138         << ASArgExpr->getSourceRange();
3139       Attr.setInvalid();
3140       return;
3141     }
3142     addrSpace.setIsSigned(false);
3143   }
3144   llvm::APSInt max(addrSpace.getBitWidth());
3145   max = Qualifiers::MaxAddressSpace;
3146   if (addrSpace > max) {
3147     S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3148       << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
3149     Attr.setInvalid();
3150     return;
3151   }
3152 
3153   unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3154   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3155 }
3156 
3157 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
3158 /// attribute on the specified type.
3159 ///
3160 /// Returns 'true' if the attribute was handled.
3161 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
3162                                        AttributeList &attr,
3163                                        QualType &type) {
3164   if (!type->isObjCRetainableType() && !type->isDependentType())
3165     return false;
3166 
3167   Sema &S = state.getSema();
3168   SourceLocation AttrLoc = attr.getLoc();
3169   if (AttrLoc.isMacroID())
3170     AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
3171 
3172   if (type.getQualifiers().getObjCLifetime()) {
3173     S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3174       << type;
3175     return true;
3176   }
3177 
3178   if (!attr.getParameterName()) {
3179     S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
3180       << "objc_ownership" << 1;
3181     attr.setInvalid();
3182     return true;
3183   }
3184 
3185   Qualifiers::ObjCLifetime lifetime;
3186   if (attr.getParameterName()->isStr("none"))
3187     lifetime = Qualifiers::OCL_ExplicitNone;
3188   else if (attr.getParameterName()->isStr("strong"))
3189     lifetime = Qualifiers::OCL_Strong;
3190   else if (attr.getParameterName()->isStr("weak"))
3191     lifetime = Qualifiers::OCL_Weak;
3192   else if (attr.getParameterName()->isStr("autoreleasing"))
3193     lifetime = Qualifiers::OCL_Autoreleasing;
3194   else {
3195     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
3196       << "objc_ownership" << attr.getParameterName();
3197     attr.setInvalid();
3198     return true;
3199   }
3200 
3201   // Consume lifetime attributes without further comment outside of
3202   // ARC mode.
3203   if (!S.getLangOptions().ObjCAutoRefCount)
3204     return true;
3205 
3206   Qualifiers qs;
3207   qs.setObjCLifetime(lifetime);
3208   QualType origType = type;
3209   type = S.Context.getQualifiedType(type, qs);
3210 
3211   // If we have a valid source location for the attribute, use an
3212   // AttributedType instead.
3213   if (AttrLoc.isValid())
3214     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
3215                                        origType, type);
3216 
3217   // Forbid __weak if the runtime doesn't support it.
3218   if (lifetime == Qualifiers::OCL_Weak &&
3219       !S.getLangOptions().ObjCRuntimeHasWeak) {
3220 
3221     // Actually, delay this until we know what we're parsing.
3222     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3223       S.DelayedDiagnostics.add(
3224           sema::DelayedDiagnostic::makeForbiddenType(
3225               S.getSourceManager().getExpansionLoc(AttrLoc),
3226               diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3227     } else {
3228       S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
3229     }
3230 
3231     attr.setInvalid();
3232     return true;
3233   }
3234 
3235   // Forbid __weak for class objects marked as
3236   // objc_arc_weak_reference_unavailable
3237   if (lifetime == Qualifiers::OCL_Weak) {
3238     QualType T = type;
3239     while (const PointerType *ptr = T->getAs<PointerType>())
3240       T = ptr->getPointeeType();
3241     if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
3242       ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
3243       if (Class->isArcWeakrefUnavailable()) {
3244           S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
3245           S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3246                  diag::note_class_declared);
3247       }
3248     }
3249   }
3250 
3251   return true;
3252 }
3253 
3254 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3255 /// attribute on the specified type.  Returns true to indicate that
3256 /// the attribute was handled, false to indicate that the type does
3257 /// not permit the attribute.
3258 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3259                                  AttributeList &attr,
3260                                  QualType &type) {
3261   Sema &S = state.getSema();
3262 
3263   // Delay if this isn't some kind of pointer.
3264   if (!type->isPointerType() &&
3265       !type->isObjCObjectPointerType() &&
3266       !type->isBlockPointerType())
3267     return false;
3268 
3269   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3270     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3271     attr.setInvalid();
3272     return true;
3273   }
3274 
3275   // Check the attribute arguments.
3276   if (!attr.getParameterName()) {
3277     S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
3278       << "objc_gc" << 1;
3279     attr.setInvalid();
3280     return true;
3281   }
3282   Qualifiers::GC GCAttr;
3283   if (attr.getNumArgs() != 0) {
3284     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3285     attr.setInvalid();
3286     return true;
3287   }
3288   if (attr.getParameterName()->isStr("weak"))
3289     GCAttr = Qualifiers::Weak;
3290   else if (attr.getParameterName()->isStr("strong"))
3291     GCAttr = Qualifiers::Strong;
3292   else {
3293     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3294       << "objc_gc" << attr.getParameterName();
3295     attr.setInvalid();
3296     return true;
3297   }
3298 
3299   QualType origType = type;
3300   type = S.Context.getObjCGCQualType(origType, GCAttr);
3301 
3302   // Make an attributed type to preserve the source information.
3303   if (attr.getLoc().isValid())
3304     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3305                                        origType, type);
3306 
3307   return true;
3308 }
3309 
3310 namespace {
3311   /// A helper class to unwrap a type down to a function for the
3312   /// purposes of applying attributes there.
3313   ///
3314   /// Use:
3315   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
3316   ///   if (unwrapped.isFunctionType()) {
3317   ///     const FunctionType *fn = unwrapped.get();
3318   ///     // change fn somehow
3319   ///     T = unwrapped.wrap(fn);
3320   ///   }
3321   struct FunctionTypeUnwrapper {
3322     enum WrapKind {
3323       Desugar,
3324       Parens,
3325       Pointer,
3326       BlockPointer,
3327       Reference,
3328       MemberPointer
3329     };
3330 
3331     QualType Original;
3332     const FunctionType *Fn;
3333     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
3334 
3335     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3336       while (true) {
3337         const Type *Ty = T.getTypePtr();
3338         if (isa<FunctionType>(Ty)) {
3339           Fn = cast<FunctionType>(Ty);
3340           return;
3341         } else if (isa<ParenType>(Ty)) {
3342           T = cast<ParenType>(Ty)->getInnerType();
3343           Stack.push_back(Parens);
3344         } else if (isa<PointerType>(Ty)) {
3345           T = cast<PointerType>(Ty)->getPointeeType();
3346           Stack.push_back(Pointer);
3347         } else if (isa<BlockPointerType>(Ty)) {
3348           T = cast<BlockPointerType>(Ty)->getPointeeType();
3349           Stack.push_back(BlockPointer);
3350         } else if (isa<MemberPointerType>(Ty)) {
3351           T = cast<MemberPointerType>(Ty)->getPointeeType();
3352           Stack.push_back(MemberPointer);
3353         } else if (isa<ReferenceType>(Ty)) {
3354           T = cast<ReferenceType>(Ty)->getPointeeType();
3355           Stack.push_back(Reference);
3356         } else {
3357           const Type *DTy = Ty->getUnqualifiedDesugaredType();
3358           if (Ty == DTy) {
3359             Fn = 0;
3360             return;
3361           }
3362 
3363           T = QualType(DTy, 0);
3364           Stack.push_back(Desugar);
3365         }
3366       }
3367     }
3368 
3369     bool isFunctionType() const { return (Fn != 0); }
3370     const FunctionType *get() const { return Fn; }
3371 
3372     QualType wrap(Sema &S, const FunctionType *New) {
3373       // If T wasn't modified from the unwrapped type, do nothing.
3374       if (New == get()) return Original;
3375 
3376       Fn = New;
3377       return wrap(S.Context, Original, 0);
3378     }
3379 
3380   private:
3381     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3382       if (I == Stack.size())
3383         return C.getQualifiedType(Fn, Old.getQualifiers());
3384 
3385       // Build up the inner type, applying the qualifiers from the old
3386       // type to the new type.
3387       SplitQualType SplitOld = Old.split();
3388 
3389       // As a special case, tail-recurse if there are no qualifiers.
3390       if (SplitOld.second.empty())
3391         return wrap(C, SplitOld.first, I);
3392       return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
3393     }
3394 
3395     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3396       if (I == Stack.size()) return QualType(Fn, 0);
3397 
3398       switch (static_cast<WrapKind>(Stack[I++])) {
3399       case Desugar:
3400         // This is the point at which we potentially lose source
3401         // information.
3402         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3403 
3404       case Parens: {
3405         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3406         return C.getParenType(New);
3407       }
3408 
3409       case Pointer: {
3410         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3411         return C.getPointerType(New);
3412       }
3413 
3414       case BlockPointer: {
3415         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3416         return C.getBlockPointerType(New);
3417       }
3418 
3419       case MemberPointer: {
3420         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3421         QualType New = wrap(C, OldMPT->getPointeeType(), I);
3422         return C.getMemberPointerType(New, OldMPT->getClass());
3423       }
3424 
3425       case Reference: {
3426         const ReferenceType *OldRef = cast<ReferenceType>(Old);
3427         QualType New = wrap(C, OldRef->getPointeeType(), I);
3428         if (isa<LValueReferenceType>(OldRef))
3429           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3430         else
3431           return C.getRValueReferenceType(New);
3432       }
3433       }
3434 
3435       llvm_unreachable("unknown wrapping kind");
3436       return QualType();
3437     }
3438   };
3439 }
3440 
3441 /// Process an individual function attribute.  Returns true to
3442 /// indicate that the attribute was handled, false if it wasn't.
3443 static bool handleFunctionTypeAttr(TypeProcessingState &state,
3444                                    AttributeList &attr,
3445                                    QualType &type) {
3446   Sema &S = state.getSema();
3447 
3448   FunctionTypeUnwrapper unwrapped(S, type);
3449 
3450   if (attr.getKind() == AttributeList::AT_noreturn) {
3451     if (S.CheckNoReturnAttr(attr))
3452       return true;
3453 
3454     // Delay if this is not a function type.
3455     if (!unwrapped.isFunctionType())
3456       return false;
3457 
3458     // Otherwise we can process right away.
3459     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3460     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3461     return true;
3462   }
3463 
3464   // ns_returns_retained is not always a type attribute, but if we got
3465   // here, we're treating it as one right now.
3466   if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
3467     assert(S.getLangOptions().ObjCAutoRefCount &&
3468            "ns_returns_retained treated as type attribute in non-ARC");
3469     if (attr.getNumArgs()) return true;
3470 
3471     // Delay if this is not a function type.
3472     if (!unwrapped.isFunctionType())
3473       return false;
3474 
3475     FunctionType::ExtInfo EI
3476       = unwrapped.get()->getExtInfo().withProducesResult(true);
3477     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3478     return true;
3479   }
3480 
3481   if (attr.getKind() == AttributeList::AT_regparm) {
3482     unsigned value;
3483     if (S.CheckRegparmAttr(attr, value))
3484       return true;
3485 
3486     // Delay if this is not a function type.
3487     if (!unwrapped.isFunctionType())
3488       return false;
3489 
3490     // Diagnose regparm with fastcall.
3491     const FunctionType *fn = unwrapped.get();
3492     CallingConv CC = fn->getCallConv();
3493     if (CC == CC_X86FastCall) {
3494       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3495         << FunctionType::getNameForCallConv(CC)
3496         << "regparm";
3497       attr.setInvalid();
3498       return true;
3499     }
3500 
3501     FunctionType::ExtInfo EI =
3502       unwrapped.get()->getExtInfo().withRegParm(value);
3503     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3504     return true;
3505   }
3506 
3507   // Otherwise, a calling convention.
3508   CallingConv CC;
3509   if (S.CheckCallingConvAttr(attr, CC))
3510     return true;
3511 
3512   // Delay if the type didn't work out to a function.
3513   if (!unwrapped.isFunctionType()) return false;
3514 
3515   const FunctionType *fn = unwrapped.get();
3516   CallingConv CCOld = fn->getCallConv();
3517   if (S.Context.getCanonicalCallConv(CC) ==
3518       S.Context.getCanonicalCallConv(CCOld)) {
3519     FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3520     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3521     return true;
3522   }
3523 
3524   if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
3525     // Should we diagnose reapplications of the same convention?
3526     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3527       << FunctionType::getNameForCallConv(CC)
3528       << FunctionType::getNameForCallConv(CCOld);
3529     attr.setInvalid();
3530     return true;
3531   }
3532 
3533   // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3534   if (CC == CC_X86FastCall) {
3535     if (isa<FunctionNoProtoType>(fn)) {
3536       S.Diag(attr.getLoc(), diag::err_cconv_knr)
3537         << FunctionType::getNameForCallConv(CC);
3538       attr.setInvalid();
3539       return true;
3540     }
3541 
3542     const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
3543     if (FnP->isVariadic()) {
3544       S.Diag(attr.getLoc(), diag::err_cconv_varargs)
3545         << FunctionType::getNameForCallConv(CC);
3546       attr.setInvalid();
3547       return true;
3548     }
3549 
3550     // Also diagnose fastcall with regparm.
3551     if (fn->getHasRegParm()) {
3552       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3553         << "regparm"
3554         << FunctionType::getNameForCallConv(CC);
3555       attr.setInvalid();
3556       return true;
3557     }
3558   }
3559 
3560   FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3561   type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3562   return true;
3563 }
3564 
3565 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3566 static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3567                                              const AttributeList &Attr,
3568                                              Sema &S) {
3569   // Check the attribute arguments.
3570   if (Attr.getNumArgs() != 1) {
3571     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3572     Attr.setInvalid();
3573     return;
3574   }
3575   Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3576   llvm::APSInt arg(32);
3577   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3578       !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3579     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3580       << "opencl_image_access" << sizeExpr->getSourceRange();
3581     Attr.setInvalid();
3582     return;
3583   }
3584   unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3585   switch (iarg) {
3586   case CLIA_read_only:
3587   case CLIA_write_only:
3588   case CLIA_read_write:
3589     // Implemented in a separate patch
3590     break;
3591   default:
3592     // Implemented in a separate patch
3593     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3594       << sizeExpr->getSourceRange();
3595     Attr.setInvalid();
3596     break;
3597   }
3598 }
3599 
3600 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
3601 /// and float scalars, although arrays, pointers, and function return values are
3602 /// allowed in conjunction with this construct. Aggregates with this attribute
3603 /// are invalid, even if they are of the same size as a corresponding scalar.
3604 /// The raw attribute should contain precisely 1 argument, the vector size for
3605 /// the variable, measured in bytes. If curType and rawAttr are well formed,
3606 /// this routine will return a new vector type.
3607 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3608                                  Sema &S) {
3609   // Check the attribute arguments.
3610   if (Attr.getNumArgs() != 1) {
3611     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3612     Attr.setInvalid();
3613     return;
3614   }
3615   Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3616   llvm::APSInt vecSize(32);
3617   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3618       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
3619     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3620       << "vector_size" << sizeExpr->getSourceRange();
3621     Attr.setInvalid();
3622     return;
3623   }
3624   // the base type must be integer or float, and can't already be a vector.
3625   if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
3626     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
3627     Attr.setInvalid();
3628     return;
3629   }
3630   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3631   // vecSize is specified in bytes - convert to bits.
3632   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3633 
3634   // the vector size needs to be an integral multiple of the type size.
3635   if (vectorSize % typeSize) {
3636     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3637       << sizeExpr->getSourceRange();
3638     Attr.setInvalid();
3639     return;
3640   }
3641   if (vectorSize == 0) {
3642     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3643       << sizeExpr->getSourceRange();
3644     Attr.setInvalid();
3645     return;
3646   }
3647 
3648   // Success! Instantiate the vector type, the number of elements is > 0, and
3649   // not required to be a power of 2, unlike GCC.
3650   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
3651                                     VectorType::GenericVector);
3652 }
3653 
3654 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
3655 /// a type.
3656 static void HandleExtVectorTypeAttr(QualType &CurType,
3657                                     const AttributeList &Attr,
3658                                     Sema &S) {
3659   Expr *sizeExpr;
3660 
3661   // Special case where the argument is a template id.
3662   if (Attr.getParameterName()) {
3663     CXXScopeSpec SS;
3664     UnqualifiedId id;
3665     id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
3666 
3667     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, id, false,
3668                                           false);
3669     if (Size.isInvalid())
3670       return;
3671 
3672     sizeExpr = Size.get();
3673   } else {
3674     // check the attribute arguments.
3675     if (Attr.getNumArgs() != 1) {
3676       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3677       return;
3678     }
3679     sizeExpr = Attr.getArg(0);
3680   }
3681 
3682   // Create the vector type.
3683   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
3684   if (!T.isNull())
3685     CurType = T;
3686 }
3687 
3688 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3689 /// "neon_polyvector_type" attributes are used to create vector types that
3690 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
3691 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
3692 /// the argument to these Neon attributes is the number of vector elements,
3693 /// not the vector size in bytes.  The vector width and element type must
3694 /// match one of the standard Neon vector types.
3695 static void HandleNeonVectorTypeAttr(QualType& CurType,
3696                                      const AttributeList &Attr, Sema &S,
3697                                      VectorType::VectorKind VecKind,
3698                                      const char *AttrName) {
3699   // Check the attribute arguments.
3700   if (Attr.getNumArgs() != 1) {
3701     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3702     Attr.setInvalid();
3703     return;
3704   }
3705   // The number of elements must be an ICE.
3706   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3707   llvm::APSInt numEltsInt(32);
3708   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3709       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3710     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3711       << AttrName << numEltsExpr->getSourceRange();
3712     Attr.setInvalid();
3713     return;
3714   }
3715   // Only certain element types are supported for Neon vectors.
3716   const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3717   if (!BTy ||
3718       (VecKind == VectorType::NeonPolyVector &&
3719        BTy->getKind() != BuiltinType::SChar &&
3720        BTy->getKind() != BuiltinType::Short) ||
3721       (BTy->getKind() != BuiltinType::SChar &&
3722        BTy->getKind() != BuiltinType::UChar &&
3723        BTy->getKind() != BuiltinType::Short &&
3724        BTy->getKind() != BuiltinType::UShort &&
3725        BTy->getKind() != BuiltinType::Int &&
3726        BTy->getKind() != BuiltinType::UInt &&
3727        BTy->getKind() != BuiltinType::LongLong &&
3728        BTy->getKind() != BuiltinType::ULongLong &&
3729        BTy->getKind() != BuiltinType::Float)) {
3730     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3731     Attr.setInvalid();
3732     return;
3733   }
3734   // The total size of the vector must be 64 or 128 bits.
3735   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3736   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3737   unsigned vecSize = typeSize * numElts;
3738   if (vecSize != 64 && vecSize != 128) {
3739     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3740     Attr.setInvalid();
3741     return;
3742   }
3743 
3744   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3745 }
3746 
3747 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3748                              bool isDeclSpec, AttributeList *attrs) {
3749   // Scan through and apply attributes to this type where it makes sense.  Some
3750   // attributes (such as __address_space__, __vector_size__, etc) apply to the
3751   // type, but others can be present in the type specifiers even though they
3752   // apply to the decl.  Here we apply type attributes and ignore the rest.
3753 
3754   AttributeList *next;
3755   do {
3756     AttributeList &attr = *attrs;
3757     next = attr.getNext();
3758 
3759     // Skip attributes that were marked to be invalid.
3760     if (attr.isInvalid())
3761       continue;
3762 
3763     // If this is an attribute we can handle, do so now,
3764     // otherwise, add it to the FnAttrs list for rechaining.
3765     switch (attr.getKind()) {
3766     default: break;
3767 
3768     case AttributeList::AT_address_space:
3769       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
3770       attr.setUsedAsTypeAttr();
3771       break;
3772     OBJC_POINTER_TYPE_ATTRS_CASELIST:
3773       if (!handleObjCPointerTypeAttr(state, attr, type))
3774         distributeObjCPointerTypeAttr(state, attr, type);
3775       attr.setUsedAsTypeAttr();
3776       break;
3777     case AttributeList::AT_vector_size:
3778       HandleVectorSizeAttr(type, attr, state.getSema());
3779       attr.setUsedAsTypeAttr();
3780       break;
3781     case AttributeList::AT_ext_vector_type:
3782       if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
3783             != DeclSpec::SCS_typedef)
3784         HandleExtVectorTypeAttr(type, attr, state.getSema());
3785       attr.setUsedAsTypeAttr();
3786       break;
3787     case AttributeList::AT_neon_vector_type:
3788       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3789                                VectorType::NeonVector, "neon_vector_type");
3790       attr.setUsedAsTypeAttr();
3791       break;
3792     case AttributeList::AT_neon_polyvector_type:
3793       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3794                                VectorType::NeonPolyVector,
3795                                "neon_polyvector_type");
3796       attr.setUsedAsTypeAttr();
3797       break;
3798     case AttributeList::AT_opencl_image_access:
3799       HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
3800       attr.setUsedAsTypeAttr();
3801       break;
3802 
3803     case AttributeList::AT_ns_returns_retained:
3804       if (!state.getSema().getLangOptions().ObjCAutoRefCount)
3805 	break;
3806       // fallthrough into the function attrs
3807 
3808     FUNCTION_TYPE_ATTRS_CASELIST:
3809       attr.setUsedAsTypeAttr();
3810 
3811       // Never process function type attributes as part of the
3812       // declaration-specifiers.
3813       if (isDeclSpec)
3814         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3815 
3816       // Otherwise, handle the possible delays.
3817       else if (!handleFunctionTypeAttr(state, attr, type))
3818         distributeFunctionTypeAttr(state, attr, type);
3819       break;
3820     }
3821   } while ((attrs = next));
3822 }
3823 
3824 /// \brief Ensure that the type of the given expression is complete.
3825 ///
3826 /// This routine checks whether the expression \p E has a complete type. If the
3827 /// expression refers to an instantiable construct, that instantiation is
3828 /// performed as needed to complete its type. Furthermore
3829 /// Sema::RequireCompleteType is called for the expression's type (or in the
3830 /// case of a reference type, the referred-to type).
3831 ///
3832 /// \param E The expression whose type is required to be complete.
3833 /// \param PD The partial diagnostic that will be printed out if the type cannot
3834 /// be completed.
3835 ///
3836 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
3837 /// otherwise.
3838 bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
3839                                    std::pair<SourceLocation,
3840                                              PartialDiagnostic> Note) {
3841   QualType T = E->getType();
3842 
3843   // Fast path the case where the type is already complete.
3844   if (!T->isIncompleteType())
3845     return false;
3846 
3847   // Incomplete array types may be completed by the initializer attached to
3848   // their definitions. For static data members of class templates we need to
3849   // instantiate the definition to get this initializer and complete the type.
3850   if (T->isIncompleteArrayType()) {
3851     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3852       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3853         if (Var->isStaticDataMember() &&
3854             Var->getInstantiatedFromStaticDataMember()) {
3855 
3856           MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3857           assert(MSInfo && "Missing member specialization information?");
3858           if (MSInfo->getTemplateSpecializationKind()
3859                 != TSK_ExplicitSpecialization) {
3860             // If we don't already have a point of instantiation, this is it.
3861             if (MSInfo->getPointOfInstantiation().isInvalid()) {
3862               MSInfo->setPointOfInstantiation(E->getLocStart());
3863 
3864               // This is a modification of an existing AST node. Notify
3865               // listeners.
3866               if (ASTMutationListener *L = getASTMutationListener())
3867                 L->StaticDataMemberInstantiated(Var);
3868             }
3869 
3870             InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
3871 
3872             // Update the type to the newly instantiated definition's type both
3873             // here and within the expression.
3874             if (VarDecl *Def = Var->getDefinition()) {
3875               DRE->setDecl(Def);
3876               T = Def->getType();
3877               DRE->setType(T);
3878               E->setType(T);
3879             }
3880           }
3881 
3882           // We still go on to try to complete the type independently, as it
3883           // may also require instantiations or diagnostics if it remains
3884           // incomplete.
3885         }
3886       }
3887     }
3888   }
3889 
3890   // FIXME: Are there other cases which require instantiating something other
3891   // than the type to complete the type of an expression?
3892 
3893   // Look through reference types and complete the referred type.
3894   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3895     T = Ref->getPointeeType();
3896 
3897   return RequireCompleteType(E->getExprLoc(), T, PD, Note);
3898 }
3899 
3900 /// @brief Ensure that the type T is a complete type.
3901 ///
3902 /// This routine checks whether the type @p T is complete in any
3903 /// context where a complete type is required. If @p T is a complete
3904 /// type, returns false. If @p T is a class template specialization,
3905 /// this routine then attempts to perform class template
3906 /// instantiation. If instantiation fails, or if @p T is incomplete
3907 /// and cannot be completed, issues the diagnostic @p diag (giving it
3908 /// the type @p T) and returns true.
3909 ///
3910 /// @param Loc  The location in the source that the incomplete type
3911 /// diagnostic should refer to.
3912 ///
3913 /// @param T  The type that this routine is examining for completeness.
3914 ///
3915 /// @param PD The partial diagnostic that will be printed out if T is not a
3916 /// complete type.
3917 ///
3918 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
3919 /// @c false otherwise.
3920 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3921                                const PartialDiagnostic &PD,
3922                                std::pair<SourceLocation,
3923                                          PartialDiagnostic> Note) {
3924   unsigned diag = PD.getDiagID();
3925 
3926   // FIXME: Add this assertion to make sure we always get instantiation points.
3927   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
3928   // FIXME: Add this assertion to help us flush out problems with
3929   // checking for dependent types and type-dependent expressions.
3930   //
3931   //  assert(!T->isDependentType() &&
3932   //         "Can't ask whether a dependent type is complete");
3933 
3934   // If we have a complete type, we're done.
3935   if (!T->isIncompleteType())
3936     return false;
3937 
3938   // If we have a class template specialization or a class member of a
3939   // class template specialization, or an array with known size of such,
3940   // try to instantiate it.
3941   QualType MaybeTemplate = T;
3942   if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
3943     MaybeTemplate = Array->getElementType();
3944   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
3945     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
3946           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
3947       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
3948         return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
3949                                                       TSK_ImplicitInstantiation,
3950                                                       /*Complain=*/diag != 0);
3951     } else if (CXXRecordDecl *Rec
3952                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
3953       if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
3954         MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
3955         assert(MSInfo && "Missing member specialization information?");
3956         // This record was instantiated from a class within a template.
3957         if (MSInfo->getTemplateSpecializationKind()
3958                                                != TSK_ExplicitSpecialization)
3959           return InstantiateClass(Loc, Rec, Pattern,
3960                                   getTemplateInstantiationArgs(Rec),
3961                                   TSK_ImplicitInstantiation,
3962                                   /*Complain=*/diag != 0);
3963       }
3964     }
3965   }
3966 
3967   if (diag == 0)
3968     return true;
3969 
3970   const TagType *Tag = T->getAs<TagType>();
3971 
3972   // Avoid diagnosing invalid decls as incomplete.
3973   if (Tag && Tag->getDecl()->isInvalidDecl())
3974     return true;
3975 
3976   // Give the external AST source a chance to complete the type.
3977   if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) {
3978     Context.getExternalSource()->CompleteType(Tag->getDecl());
3979     if (!Tag->isIncompleteType())
3980       return false;
3981   }
3982 
3983   // We have an incomplete type. Produce a diagnostic.
3984   Diag(Loc, PD) << T;
3985 
3986   // If we have a note, produce it.
3987   if (!Note.first.isInvalid())
3988     Diag(Note.first, Note.second);
3989 
3990   // If the type was a forward declaration of a class/struct/union
3991   // type, produce a note.
3992   if (Tag && !Tag->getDecl()->isInvalidDecl())
3993     Diag(Tag->getDecl()->getLocation(),
3994          Tag->isBeingDefined() ? diag::note_type_being_defined
3995                                : diag::note_forward_declaration)
3996         << QualType(Tag, 0);
3997 
3998   return true;
3999 }
4000 
4001 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4002                                const PartialDiagnostic &PD) {
4003   return RequireCompleteType(Loc, T, PD,
4004                              std::make_pair(SourceLocation(), PDiag(0)));
4005 }
4006 
4007 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4008                                unsigned DiagID) {
4009   return RequireCompleteType(Loc, T, PDiag(DiagID),
4010                              std::make_pair(SourceLocation(), PDiag(0)));
4011 }
4012 
4013 /// @brief Ensure that the type T is a literal type.
4014 ///
4015 /// This routine checks whether the type @p T is a literal type. If @p T is an
4016 /// incomplete type, an attempt is made to complete it. If @p T is a literal
4017 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4018 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4019 /// it the type @p T), along with notes explaining why the type is not a
4020 /// literal type, and returns true.
4021 ///
4022 /// @param Loc  The location in the source that the non-literal type
4023 /// diagnostic should refer to.
4024 ///
4025 /// @param T  The type that this routine is examining for literalness.
4026 ///
4027 /// @param PD The partial diagnostic that will be printed out if T is not a
4028 /// literal type.
4029 ///
4030 /// @param AllowIncompleteType If true, an incomplete type will be considered
4031 /// acceptable.
4032 ///
4033 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4034 /// @c false otherwise.
4035 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
4036                               const PartialDiagnostic &PD,
4037                               bool AllowIncompleteType) {
4038   assert(!T->isDependentType() && "type should not be dependent");
4039 
4040   bool Incomplete = RequireCompleteType(Loc, T, 0);
4041   if (T->isLiteralType() || (AllowIncompleteType && Incomplete))
4042     return false;
4043 
4044   if (PD.getDiagID() == 0)
4045     return true;
4046 
4047   Diag(Loc, PD) << T;
4048 
4049   if (T->isVariableArrayType())
4050     return true;
4051 
4052   const RecordType *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>();
4053   if (!RT)
4054     return true;
4055 
4056   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4057 
4058   // If the class has virtual base classes, then it's not an aggregate, and
4059   // cannot have any constexpr constructors, so is non-literal. This is better
4060   // to diagnose than the resulting absence of constexpr constructors.
4061   if (RD->getNumVBases()) {
4062     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
4063       << RD->isStruct() << RD->getNumVBases();
4064     for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4065            E = RD->vbases_end(); I != E; ++I)
4066       Diag(I->getSourceRange().getBegin(),
4067            diag::note_constexpr_virtual_base_here) << I->getSourceRange();
4068   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor()) {
4069     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
4070 
4071     switch (RD->getTemplateSpecializationKind()) {
4072     case TSK_Undeclared:
4073     case TSK_ExplicitSpecialization:
4074       break;
4075 
4076     case TSK_ImplicitInstantiation:
4077     case TSK_ExplicitInstantiationDeclaration:
4078     case TSK_ExplicitInstantiationDefinition:
4079       // If the base template had constexpr constructors which were
4080       // instantiated as non-constexpr constructors, explain why.
4081       for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4082            E = RD->ctor_end(); I != E; ++I) {
4083         if ((*I)->isCopyConstructor() || (*I)->isMoveConstructor())
4084           continue;
4085 
4086         FunctionDecl *Base = (*I)->getInstantiatedFromMemberFunction();
4087         if (Base && Base->isConstexpr())
4088           CheckConstexprFunctionDecl(*I, CCK_NoteNonConstexprInstantiation);
4089       }
4090     }
4091   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4092     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4093          E = RD->bases_end(); I != E; ++I) {
4094       if (!I->getType()->isLiteralType()) {
4095         Diag(I->getSourceRange().getBegin(),
4096              diag::note_non_literal_base_class)
4097           << RD << I->getType() << I->getSourceRange();
4098         return true;
4099       }
4100     }
4101     for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4102          E = RD->field_end(); I != E; ++I) {
4103       if (!(*I)->getType()->isLiteralType()) {
4104         Diag((*I)->getLocation(), diag::note_non_literal_field)
4105           << RD << (*I) << (*I)->getType();
4106         return true;
4107       }
4108     }
4109   } else if (!RD->hasTrivialDestructor()) {
4110     // All fields and bases are of literal types, so have trivial destructors.
4111     // If this class's destructor is non-trivial it must be user-declared.
4112     CXXDestructorDecl *Dtor = RD->getDestructor();
4113     assert(Dtor && "class has literal fields and bases but no dtor?");
4114     if (!Dtor)
4115       return true;
4116 
4117     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4118          diag::note_non_literal_user_provided_dtor :
4119          diag::note_non_literal_nontrivial_dtor) << RD;
4120   }
4121 
4122   return true;
4123 }
4124 
4125 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4126 /// and qualified by the nested-name-specifier contained in SS.
4127 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4128                                  const CXXScopeSpec &SS, QualType T) {
4129   if (T.isNull())
4130     return T;
4131   NestedNameSpecifier *NNS;
4132   if (SS.isValid())
4133     NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4134   else {
4135     if (Keyword == ETK_None)
4136       return T;
4137     NNS = 0;
4138   }
4139   return Context.getElaboratedType(Keyword, NNS, T);
4140 }
4141 
4142 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
4143   ExprResult ER = CheckPlaceholderExpr(E);
4144   if (ER.isInvalid()) return QualType();
4145   E = ER.take();
4146 
4147   if (!E->isTypeDependent()) {
4148     QualType T = E->getType();
4149     if (const TagType *TT = T->getAs<TagType>())
4150       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
4151   }
4152   return Context.getTypeOfExprType(E);
4153 }
4154 
4155 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
4156   ExprResult ER = CheckPlaceholderExpr(E);
4157   if (ER.isInvalid()) return QualType();
4158   E = ER.take();
4159 
4160   return Context.getDecltypeType(E);
4161 }
4162 
4163 QualType Sema::BuildUnaryTransformType(QualType BaseType,
4164                                        UnaryTransformType::UTTKind UKind,
4165                                        SourceLocation Loc) {
4166   switch (UKind) {
4167   case UnaryTransformType::EnumUnderlyingType:
4168     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4169       Diag(Loc, diag::err_only_enums_have_underlying_types);
4170       return QualType();
4171     } else {
4172       QualType Underlying = BaseType;
4173       if (!BaseType->isDependentType()) {
4174         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4175         assert(ED && "EnumType has no EnumDecl");
4176         DiagnoseUseOfDecl(ED, Loc);
4177         Underlying = ED->getIntegerType();
4178       }
4179       assert(!Underlying.isNull());
4180       return Context.getUnaryTransformType(BaseType, Underlying,
4181                                         UnaryTransformType::EnumUnderlyingType);
4182     }
4183   }
4184   llvm_unreachable("unknown unary transform type");
4185 }
4186