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