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