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