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