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