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           // Look for 'void'.  void is allowed only as a single argument to a
2848           // function with no other parameters (C99 6.7.5.3p10).  We record
2849           // int(void) as a FunctionProtoType with an empty argument list.
2850           if (ArgTy->isVoidType()) {
2851             // If this is something like 'float(int, void)', reject it.  'void'
2852             // is an incomplete type (C99 6.2.5p19) and function decls cannot
2853             // have arguments of incomplete type.
2854             if (FTI.NumArgs != 1 || FTI.isVariadic) {
2855               S.Diag(DeclType.Loc, diag::err_void_only_param);
2856               ArgTy = Context.IntTy;
2857               Param->setType(ArgTy);
2858             } else if (FTI.ArgInfo[i].Ident) {
2859               // Reject, but continue to parse 'int(void abc)'.
2860               S.Diag(FTI.ArgInfo[i].IdentLoc,
2861                    diag::err_param_with_void_type);
2862               ArgTy = Context.IntTy;
2863               Param->setType(ArgTy);
2864             } else {
2865               // Reject, but continue to parse 'float(const void)'.
2866               if (ArgTy.hasQualifiers())
2867                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2868 
2869               // Do not add 'void' to the ArgTys list.
2870               break;
2871             }
2872           } else if (ArgTy->isHalfType()) {
2873             // Disallow half FP arguments.
2874             // FIXME: This really should be in BuildFunctionType.
2875             if (S.getLangOpts().OpenCL) {
2876               if (!S.getOpenCLOptions().cl_khr_fp16) {
2877                 S.Diag(Param->getLocation(),
2878                   diag::err_opencl_half_argument) << ArgTy;
2879                 D.setInvalidType();
2880                 Param->setInvalidDecl();
2881               }
2882             } else {
2883               S.Diag(Param->getLocation(),
2884                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
2885               D.setInvalidType();
2886             }
2887           } else if (!FTI.hasPrototype) {
2888             if (ArgTy->isPromotableIntegerType()) {
2889               ArgTy = Context.getPromotedIntegerType(ArgTy);
2890               Param->setKNRPromoted(true);
2891             } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
2892               if (BTy->getKind() == BuiltinType::Float) {
2893                 ArgTy = Context.DoubleTy;
2894                 Param->setKNRPromoted(true);
2895               }
2896             }
2897           }
2898 
2899           if (LangOpts.ObjCAutoRefCount) {
2900             bool Consumed = Param->hasAttr<NSConsumedAttr>();
2901             ConsumedArguments.push_back(Consumed);
2902             HasAnyConsumedArguments |= Consumed;
2903           }
2904 
2905           ArgTys.push_back(ArgTy);
2906         }
2907 
2908         if (HasAnyConsumedArguments)
2909           EPI.ConsumedArguments = ConsumedArguments.data();
2910 
2911         SmallVector<QualType, 4> Exceptions;
2912         SmallVector<ParsedType, 2> DynamicExceptions;
2913         SmallVector<SourceRange, 2> DynamicExceptionRanges;
2914         Expr *NoexceptExpr = 0;
2915 
2916         if (FTI.getExceptionSpecType() == EST_Dynamic) {
2917           // FIXME: It's rather inefficient to have to split into two vectors
2918           // here.
2919           unsigned N = FTI.NumExceptions;
2920           DynamicExceptions.reserve(N);
2921           DynamicExceptionRanges.reserve(N);
2922           for (unsigned I = 0; I != N; ++I) {
2923             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
2924             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
2925           }
2926         } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
2927           NoexceptExpr = FTI.NoexceptExpr;
2928         }
2929 
2930         S.checkExceptionSpecification(FTI.getExceptionSpecType(),
2931                                       DynamicExceptions,
2932                                       DynamicExceptionRanges,
2933                                       NoexceptExpr,
2934                                       Exceptions,
2935                                       EPI);
2936 
2937         T = Context.getFunctionType(T, ArgTys, EPI);
2938       }
2939 
2940       break;
2941     }
2942     case DeclaratorChunk::MemberPointer:
2943       // The scope spec must refer to a class, or be dependent.
2944       CXXScopeSpec &SS = DeclType.Mem.Scope();
2945       QualType ClsType;
2946       if (SS.isInvalid()) {
2947         // Avoid emitting extra errors if we already errored on the scope.
2948         D.setInvalidType(true);
2949       } else if (S.isDependentScopeSpecifier(SS) ||
2950                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
2951         NestedNameSpecifier *NNS
2952           = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2953         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2954         switch (NNS->getKind()) {
2955         case NestedNameSpecifier::Identifier:
2956           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
2957                                                  NNS->getAsIdentifier());
2958           break;
2959 
2960         case NestedNameSpecifier::Namespace:
2961         case NestedNameSpecifier::NamespaceAlias:
2962         case NestedNameSpecifier::Global:
2963           llvm_unreachable("Nested-name-specifier must name a type");
2964 
2965         case NestedNameSpecifier::TypeSpec:
2966         case NestedNameSpecifier::TypeSpecWithTemplate:
2967           ClsType = QualType(NNS->getAsType(), 0);
2968           // Note: if the NNS has a prefix and ClsType is a nondependent
2969           // TemplateSpecializationType, then the NNS prefix is NOT included
2970           // in ClsType; hence we wrap ClsType into an ElaboratedType.
2971           // NOTE: in particular, no wrap occurs if ClsType already is an
2972           // Elaborated, DependentName, or DependentTemplateSpecialization.
2973           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
2974             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
2975           break;
2976         }
2977       } else {
2978         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
2979              diag::err_illegal_decl_mempointer_in_nonclass)
2980           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2981           << DeclType.Mem.Scope().getRange();
2982         D.setInvalidType(true);
2983       }
2984 
2985       if (!ClsType.isNull())
2986         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
2987       if (T.isNull()) {
2988         T = Context.IntTy;
2989         D.setInvalidType(true);
2990       } else if (DeclType.Mem.TypeQuals) {
2991         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
2992       }
2993       break;
2994     }
2995 
2996     if (T.isNull()) {
2997       D.setInvalidType(true);
2998       T = Context.IntTy;
2999     }
3000 
3001     // See if there are any attributes on this declarator chunk.
3002     if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
3003       processTypeAttrs(state, T, TAL_DeclChunk, attrs);
3004   }
3005 
3006   if (LangOpts.CPlusPlus && T->isFunctionType()) {
3007     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
3008     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
3009 
3010     // C++ 8.3.5p4:
3011     //   A cv-qualifier-seq shall only be part of the function type
3012     //   for a nonstatic member function, the function type to which a pointer
3013     //   to member refers, or the top-level function type of a function typedef
3014     //   declaration.
3015     //
3016     // Core issue 547 also allows cv-qualifiers on function types that are
3017     // top-level template type arguments.
3018     bool FreeFunction;
3019     if (!D.getCXXScopeSpec().isSet()) {
3020       FreeFunction = ((D.getContext() != Declarator::MemberContext &&
3021                        D.getContext() != Declarator::LambdaExprContext) ||
3022                       D.getDeclSpec().isFriendSpecified());
3023     } else {
3024       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
3025       FreeFunction = (DC && !DC->isRecord());
3026     }
3027 
3028     // C++11 [dcl.fct]p6 (w/DR1417):
3029     // An attempt to specify a function type with a cv-qualifier-seq or a
3030     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
3031     //  - the function type for a non-static member function,
3032     //  - the function type to which a pointer to member refers,
3033     //  - the top-level function type of a function typedef declaration or
3034     //    alias-declaration,
3035     //  - the type-id in the default argument of a type-parameter, or
3036     //  - the type-id of a template-argument for a type-parameter
3037     if (IsQualifiedFunction &&
3038         !(!FreeFunction &&
3039           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
3040         !IsTypedefName &&
3041         D.getContext() != Declarator::TemplateTypeArgContext) {
3042       SourceLocation Loc = D.getLocStart();
3043       SourceRange RemovalRange;
3044       unsigned I;
3045       if (D.isFunctionDeclarator(I)) {
3046         SmallVector<SourceLocation, 4> RemovalLocs;
3047         const DeclaratorChunk &Chunk = D.getTypeObject(I);
3048         assert(Chunk.Kind == DeclaratorChunk::Function);
3049         if (Chunk.Fun.hasRefQualifier())
3050           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
3051         if (Chunk.Fun.TypeQuals & Qualifiers::Const)
3052           RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
3053         if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
3054           RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
3055         // FIXME: We do not track the location of the __restrict qualifier.
3056         //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
3057         //  RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
3058         if (!RemovalLocs.empty()) {
3059           std::sort(RemovalLocs.begin(), RemovalLocs.end(),
3060                     BeforeThanCompare<SourceLocation>(S.getSourceManager()));
3061           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
3062           Loc = RemovalLocs.front();
3063         }
3064       }
3065 
3066       S.Diag(Loc, diag::err_invalid_qualified_function_type)
3067         << FreeFunction << D.isFunctionDeclarator() << T
3068         << getFunctionQualifiersAsString(FnTy)
3069         << FixItHint::CreateRemoval(RemovalRange);
3070 
3071       // Strip the cv-qualifiers and ref-qualifiers from the type.
3072       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
3073       EPI.TypeQuals = 0;
3074       EPI.RefQualifier = RQ_None;
3075 
3076       T = Context.getFunctionType(FnTy->getResultType(), FnTy->getArgTypes(),
3077                                   EPI);
3078       // Rebuild any parens around the identifier in the function type.
3079       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3080         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
3081           break;
3082         T = S.BuildParenType(T);
3083       }
3084     }
3085   }
3086 
3087   // Apply any undistributed attributes from the declarator.
3088   if (!T.isNull())
3089     if (AttributeList *attrs = D.getAttributes())
3090       processTypeAttrs(state, T, TAL_DeclName, attrs);
3091 
3092   // Diagnose any ignored type attributes.
3093   if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
3094 
3095   // C++0x [dcl.constexpr]p9:
3096   //  A constexpr specifier used in an object declaration declares the object
3097   //  as const.
3098   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
3099     T.addConst();
3100   }
3101 
3102   // If there was an ellipsis in the declarator, the declaration declares a
3103   // parameter pack whose type may be a pack expansion type.
3104   if (D.hasEllipsis() && !T.isNull()) {
3105     // C++0x [dcl.fct]p13:
3106     //   A declarator-id or abstract-declarator containing an ellipsis shall
3107     //   only be used in a parameter-declaration. Such a parameter-declaration
3108     //   is a parameter pack (14.5.3). [...]
3109     switch (D.getContext()) {
3110     case Declarator::PrototypeContext:
3111       // C++0x [dcl.fct]p13:
3112       //   [...] When it is part of a parameter-declaration-clause, the
3113       //   parameter pack is a function parameter pack (14.5.3). The type T
3114       //   of the declarator-id of the function parameter pack shall contain
3115       //   a template parameter pack; each template parameter pack in T is
3116       //   expanded by the function parameter pack.
3117       //
3118       // We represent function parameter packs as function parameters whose
3119       // type is a pack expansion.
3120       if (!T->containsUnexpandedParameterPack()) {
3121         S.Diag(D.getEllipsisLoc(),
3122              diag::err_function_parameter_pack_without_parameter_packs)
3123           << T <<  D.getSourceRange();
3124         D.setEllipsisLoc(SourceLocation());
3125       } else {
3126         T = Context.getPackExpansionType(T, None);
3127       }
3128       break;
3129 
3130     case Declarator::TemplateParamContext:
3131       // C++0x [temp.param]p15:
3132       //   If a template-parameter is a [...] is a parameter-declaration that
3133       //   declares a parameter pack (8.3.5), then the template-parameter is a
3134       //   template parameter pack (14.5.3).
3135       //
3136       // Note: core issue 778 clarifies that, if there are any unexpanded
3137       // parameter packs in the type of the non-type template parameter, then
3138       // it expands those parameter packs.
3139       if (T->containsUnexpandedParameterPack())
3140         T = Context.getPackExpansionType(T, None);
3141       else
3142         S.Diag(D.getEllipsisLoc(),
3143                LangOpts.CPlusPlus11
3144                  ? diag::warn_cxx98_compat_variadic_templates
3145                  : diag::ext_variadic_templates);
3146       break;
3147 
3148     case Declarator::FileContext:
3149     case Declarator::KNRTypeListContext:
3150     case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
3151     case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
3152     case Declarator::TypeNameContext:
3153     case Declarator::CXXNewContext:
3154     case Declarator::AliasDeclContext:
3155     case Declarator::AliasTemplateContext:
3156     case Declarator::MemberContext:
3157     case Declarator::BlockContext:
3158     case Declarator::ForContext:
3159     case Declarator::ConditionContext:
3160     case Declarator::CXXCatchContext:
3161     case Declarator::ObjCCatchContext:
3162     case Declarator::BlockLiteralContext:
3163     case Declarator::LambdaExprContext:
3164     case Declarator::ConversionIdContext:
3165     case Declarator::TrailingReturnContext:
3166     case Declarator::TemplateTypeArgContext:
3167       // FIXME: We may want to allow parameter packs in block-literal contexts
3168       // in the future.
3169       S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
3170       D.setEllipsisLoc(SourceLocation());
3171       break;
3172     }
3173   }
3174 
3175   if (T.isNull())
3176     return Context.getNullTypeSourceInfo();
3177   else if (D.isInvalidType())
3178     return Context.getTrivialTypeSourceInfo(T);
3179 
3180   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
3181 }
3182 
3183 /// GetTypeForDeclarator - Convert the type for the specified
3184 /// declarator to Type instances.
3185 ///
3186 /// The result of this call will never be null, but the associated
3187 /// type may be a null type if there's an unrecoverable error.
3188 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
3189   // Determine the type of the declarator. Not all forms of declarator
3190   // have a type.
3191 
3192   TypeProcessingState state(*this, D);
3193 
3194   TypeSourceInfo *ReturnTypeInfo = 0;
3195   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3196   if (T.isNull())
3197     return Context.getNullTypeSourceInfo();
3198 
3199   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
3200     inferARCWriteback(state, T);
3201 
3202   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
3203 }
3204 
3205 static void transferARCOwnershipToDeclSpec(Sema &S,
3206                                            QualType &declSpecTy,
3207                                            Qualifiers::ObjCLifetime ownership) {
3208   if (declSpecTy->isObjCRetainableType() &&
3209       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
3210     Qualifiers qs;
3211     qs.addObjCLifetime(ownership);
3212     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
3213   }
3214 }
3215 
3216 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3217                                             Qualifiers::ObjCLifetime ownership,
3218                                             unsigned chunkIndex) {
3219   Sema &S = state.getSema();
3220   Declarator &D = state.getDeclarator();
3221 
3222   // Look for an explicit lifetime attribute.
3223   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
3224   for (const AttributeList *attr = chunk.getAttrs(); attr;
3225          attr = attr->getNext())
3226     if (attr->getKind() == AttributeList::AT_ObjCOwnership)
3227       return;
3228 
3229   const char *attrStr = 0;
3230   switch (ownership) {
3231   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
3232   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
3233   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
3234   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
3235   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
3236   }
3237 
3238   // If there wasn't one, add one (with an invalid source location
3239   // so that we don't make an AttributedType for it).
3240   AttributeList *attr = D.getAttributePool()
3241     .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
3242             /*scope*/ 0, SourceLocation(),
3243             &S.Context.Idents.get(attrStr), SourceLocation(),
3244             /*args*/ 0, 0, AttributeList::AS_GNU);
3245   spliceAttrIntoList(*attr, chunk.getAttrListRef());
3246 
3247   // TODO: mark whether we did this inference?
3248 }
3249 
3250 /// \brief Used for transferring ownership in casts resulting in l-values.
3251 static void transferARCOwnership(TypeProcessingState &state,
3252                                  QualType &declSpecTy,
3253                                  Qualifiers::ObjCLifetime ownership) {
3254   Sema &S = state.getSema();
3255   Declarator &D = state.getDeclarator();
3256 
3257   int inner = -1;
3258   bool hasIndirection = false;
3259   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3260     DeclaratorChunk &chunk = D.getTypeObject(i);
3261     switch (chunk.Kind) {
3262     case DeclaratorChunk::Paren:
3263       // Ignore parens.
3264       break;
3265 
3266     case DeclaratorChunk::Array:
3267     case DeclaratorChunk::Reference:
3268     case DeclaratorChunk::Pointer:
3269       if (inner != -1)
3270         hasIndirection = true;
3271       inner = i;
3272       break;
3273 
3274     case DeclaratorChunk::BlockPointer:
3275       if (inner != -1)
3276         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3277       return;
3278 
3279     case DeclaratorChunk::Function:
3280     case DeclaratorChunk::MemberPointer:
3281       return;
3282     }
3283   }
3284 
3285   if (inner == -1)
3286     return;
3287 
3288   DeclaratorChunk &chunk = D.getTypeObject(inner);
3289   if (chunk.Kind == DeclaratorChunk::Pointer) {
3290     if (declSpecTy->isObjCRetainableType())
3291       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3292     if (declSpecTy->isObjCObjectType() && hasIndirection)
3293       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3294   } else {
3295     assert(chunk.Kind == DeclaratorChunk::Array ||
3296            chunk.Kind == DeclaratorChunk::Reference);
3297     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3298   }
3299 }
3300 
3301 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3302   TypeProcessingState state(*this, D);
3303 
3304   TypeSourceInfo *ReturnTypeInfo = 0;
3305   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3306   if (declSpecTy.isNull())
3307     return Context.getNullTypeSourceInfo();
3308 
3309   if (getLangOpts().ObjCAutoRefCount) {
3310     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
3311     if (ownership != Qualifiers::OCL_None)
3312       transferARCOwnership(state, declSpecTy, ownership);
3313   }
3314 
3315   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
3316 }
3317 
3318 /// Map an AttributedType::Kind to an AttributeList::Kind.
3319 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
3320   switch (kind) {
3321   case AttributedType::attr_address_space:
3322     return AttributeList::AT_AddressSpace;
3323   case AttributedType::attr_regparm:
3324     return AttributeList::AT_Regparm;
3325   case AttributedType::attr_vector_size:
3326     return AttributeList::AT_VectorSize;
3327   case AttributedType::attr_neon_vector_type:
3328     return AttributeList::AT_NeonVectorType;
3329   case AttributedType::attr_neon_polyvector_type:
3330     return AttributeList::AT_NeonPolyVectorType;
3331   case AttributedType::attr_objc_gc:
3332     return AttributeList::AT_ObjCGC;
3333   case AttributedType::attr_objc_ownership:
3334     return AttributeList::AT_ObjCOwnership;
3335   case AttributedType::attr_noreturn:
3336     return AttributeList::AT_NoReturn;
3337   case AttributedType::attr_cdecl:
3338     return AttributeList::AT_CDecl;
3339   case AttributedType::attr_fastcall:
3340     return AttributeList::AT_FastCall;
3341   case AttributedType::attr_stdcall:
3342     return AttributeList::AT_StdCall;
3343   case AttributedType::attr_thiscall:
3344     return AttributeList::AT_ThisCall;
3345   case AttributedType::attr_pascal:
3346     return AttributeList::AT_Pascal;
3347   case AttributedType::attr_pcs:
3348     return AttributeList::AT_Pcs;
3349   case AttributedType::attr_pnaclcall:
3350     return AttributeList::AT_PnaclCall;
3351   case AttributedType::attr_inteloclbicc:
3352     return AttributeList::AT_IntelOclBicc;
3353   case AttributedType::attr_ptr32:
3354     return AttributeList::AT_Ptr32;
3355   case AttributedType::attr_ptr64:
3356     return AttributeList::AT_Ptr64;
3357   case AttributedType::attr_sptr:
3358     return AttributeList::AT_SPtr;
3359   case AttributedType::attr_uptr:
3360     return AttributeList::AT_UPtr;
3361   }
3362   llvm_unreachable("unexpected attribute kind!");
3363 }
3364 
3365 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
3366                                   const AttributeList *attrs) {
3367   AttributedType::Kind kind = TL.getAttrKind();
3368 
3369   assert(attrs && "no type attributes in the expected location!");
3370   AttributeList::Kind parsedKind = getAttrListKind(kind);
3371   while (attrs->getKind() != parsedKind) {
3372     attrs = attrs->getNext();
3373     assert(attrs && "no matching attribute in expected location!");
3374   }
3375 
3376   TL.setAttrNameLoc(attrs->getLoc());
3377   if (TL.hasAttrExprOperand())
3378     TL.setAttrExprOperand(attrs->getArg(0));
3379   else if (TL.hasAttrEnumOperand())
3380     TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
3381 
3382   // FIXME: preserve this information to here.
3383   if (TL.hasAttrOperand())
3384     TL.setAttrOperandParensRange(SourceRange());
3385 }
3386 
3387 namespace {
3388   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
3389     ASTContext &Context;
3390     const DeclSpec &DS;
3391 
3392   public:
3393     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
3394       : Context(Context), DS(DS) {}
3395 
3396     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3397       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3398       Visit(TL.getModifiedLoc());
3399     }
3400     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3401       Visit(TL.getUnqualifiedLoc());
3402     }
3403     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3404       TL.setNameLoc(DS.getTypeSpecTypeLoc());
3405     }
3406     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3407       TL.setNameLoc(DS.getTypeSpecTypeLoc());
3408       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3409       // addition field. What we have is good enough for dispay of location
3410       // of 'fixit' on interface name.
3411       TL.setNameEndLoc(DS.getLocEnd());
3412     }
3413     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3414       // Handle the base type, which might not have been written explicitly.
3415       if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3416         TL.setHasBaseTypeAsWritten(false);
3417         TL.getBaseLoc().initialize(Context, SourceLocation());
3418       } else {
3419         TL.setHasBaseTypeAsWritten(true);
3420         Visit(TL.getBaseLoc());
3421       }
3422 
3423       // Protocol qualifiers.
3424       if (DS.getProtocolQualifiers()) {
3425         assert(TL.getNumProtocols() > 0);
3426         assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3427         TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3428         TL.setRAngleLoc(DS.getSourceRange().getEnd());
3429         for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3430           TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3431       } else {
3432         assert(TL.getNumProtocols() == 0);
3433         TL.setLAngleLoc(SourceLocation());
3434         TL.setRAngleLoc(SourceLocation());
3435       }
3436     }
3437     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3438       TL.setStarLoc(SourceLocation());
3439       Visit(TL.getPointeeLoc());
3440     }
3441     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
3442       TypeSourceInfo *TInfo = 0;
3443       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3444 
3445       // If we got no declarator info from previous Sema routines,
3446       // just fill with the typespec loc.
3447       if (!TInfo) {
3448         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
3449         return;
3450       }
3451 
3452       TypeLoc OldTL = TInfo->getTypeLoc();
3453       if (TInfo->getType()->getAs<ElaboratedType>()) {
3454         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
3455         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
3456             .castAs<TemplateSpecializationTypeLoc>();
3457         TL.copy(NamedTL);
3458       } else {
3459         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
3460         assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
3461       }
3462 
3463     }
3464     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3465       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3466       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3467       TL.setParensRange(DS.getTypeofParensRange());
3468     }
3469     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3470       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3471       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3472       TL.setParensRange(DS.getTypeofParensRange());
3473       assert(DS.getRepAsType());
3474       TypeSourceInfo *TInfo = 0;
3475       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3476       TL.setUnderlyingTInfo(TInfo);
3477     }
3478     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3479       // FIXME: This holds only because we only have one unary transform.
3480       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3481       TL.setKWLoc(DS.getTypeSpecTypeLoc());
3482       TL.setParensRange(DS.getTypeofParensRange());
3483       assert(DS.getRepAsType());
3484       TypeSourceInfo *TInfo = 0;
3485       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3486       TL.setUnderlyingTInfo(TInfo);
3487     }
3488     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3489       // By default, use the source location of the type specifier.
3490       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3491       if (TL.needsExtraLocalData()) {
3492         // Set info for the written builtin specifiers.
3493         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3494         // Try to have a meaningful source location.
3495         if (TL.getWrittenSignSpec() != TSS_unspecified)
3496           // Sign spec loc overrides the others (e.g., 'unsigned long').
3497           TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3498         else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3499           // Width spec loc overrides type spec loc (e.g., 'short int').
3500           TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3501       }
3502     }
3503     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3504       ElaboratedTypeKeyword Keyword
3505         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
3506       if (DS.getTypeSpecType() == TST_typename) {
3507         TypeSourceInfo *TInfo = 0;
3508         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3509         if (TInfo) {
3510           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
3511           return;
3512         }
3513       }
3514       TL.setElaboratedKeywordLoc(Keyword != ETK_None
3515                                  ? DS.getTypeSpecTypeLoc()
3516                                  : SourceLocation());
3517       const CXXScopeSpec& SS = DS.getTypeSpecScope();
3518       TL.setQualifierLoc(SS.getWithLocInContext(Context));
3519       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3520     }
3521     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3522       assert(DS.getTypeSpecType() == TST_typename);
3523       TypeSourceInfo *TInfo = 0;
3524       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3525       assert(TInfo);
3526       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
3527     }
3528     void VisitDependentTemplateSpecializationTypeLoc(
3529                                  DependentTemplateSpecializationTypeLoc TL) {
3530       assert(DS.getTypeSpecType() == TST_typename);
3531       TypeSourceInfo *TInfo = 0;
3532       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3533       assert(TInfo);
3534       TL.copy(
3535           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
3536     }
3537     void VisitTagTypeLoc(TagTypeLoc TL) {
3538       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
3539     }
3540     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3541       // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
3542       // or an _Atomic qualifier.
3543       if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
3544         TL.setKWLoc(DS.getTypeSpecTypeLoc());
3545         TL.setParensRange(DS.getTypeofParensRange());
3546 
3547         TypeSourceInfo *TInfo = 0;
3548         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3549         assert(TInfo);
3550         TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
3551       } else {
3552         TL.setKWLoc(DS.getAtomicSpecLoc());
3553         // No parens, to indicate this was spelled as an _Atomic qualifier.
3554         TL.setParensRange(SourceRange());
3555         Visit(TL.getValueLoc());
3556       }
3557     }
3558 
3559     void VisitTypeLoc(TypeLoc TL) {
3560       // FIXME: add other typespec types and change this to an assert.
3561       TL.initialize(Context, DS.getTypeSpecTypeLoc());
3562     }
3563   };
3564 
3565   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
3566     ASTContext &Context;
3567     const DeclaratorChunk &Chunk;
3568 
3569   public:
3570     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3571       : Context(Context), Chunk(Chunk) {}
3572 
3573     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3574       llvm_unreachable("qualified type locs not expected here!");
3575     }
3576     void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
3577       llvm_unreachable("decayed type locs not expected here!");
3578     }
3579 
3580     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3581       fillAttributedTypeLoc(TL, Chunk.getAttrs());
3582     }
3583     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3584       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3585       TL.setCaretLoc(Chunk.Loc);
3586     }
3587     void VisitPointerTypeLoc(PointerTypeLoc TL) {
3588       assert(Chunk.Kind == DeclaratorChunk::Pointer);
3589       TL.setStarLoc(Chunk.Loc);
3590     }
3591     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3592       assert(Chunk.Kind == DeclaratorChunk::Pointer);
3593       TL.setStarLoc(Chunk.Loc);
3594     }
3595     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3596       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
3597       const CXXScopeSpec& SS = Chunk.Mem.Scope();
3598       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3599 
3600       const Type* ClsTy = TL.getClass();
3601       QualType ClsQT = QualType(ClsTy, 0);
3602       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3603       // Now copy source location info into the type loc component.
3604       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3605       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3606       case NestedNameSpecifier::Identifier:
3607         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3608         {
3609           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
3610           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
3611           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3612           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3613         }
3614         break;
3615 
3616       case NestedNameSpecifier::TypeSpec:
3617       case NestedNameSpecifier::TypeSpecWithTemplate:
3618         if (isa<ElaboratedType>(ClsTy)) {
3619           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
3620           ETLoc.setElaboratedKeywordLoc(SourceLocation());
3621           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3622           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3623           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3624         } else {
3625           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3626         }
3627         break;
3628 
3629       case NestedNameSpecifier::Namespace:
3630       case NestedNameSpecifier::NamespaceAlias:
3631       case NestedNameSpecifier::Global:
3632         llvm_unreachable("Nested-name-specifier must name a type");
3633       }
3634 
3635       // Finally fill in MemberPointerLocInfo fields.
3636       TL.setStarLoc(Chunk.Loc);
3637       TL.setClassTInfo(ClsTInfo);
3638     }
3639     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3640       assert(Chunk.Kind == DeclaratorChunk::Reference);
3641       // 'Amp' is misleading: this might have been originally
3642       /// spelled with AmpAmp.
3643       TL.setAmpLoc(Chunk.Loc);
3644     }
3645     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3646       assert(Chunk.Kind == DeclaratorChunk::Reference);
3647       assert(!Chunk.Ref.LValueRef);
3648       TL.setAmpAmpLoc(Chunk.Loc);
3649     }
3650     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3651       assert(Chunk.Kind == DeclaratorChunk::Array);
3652       TL.setLBracketLoc(Chunk.Loc);
3653       TL.setRBracketLoc(Chunk.EndLoc);
3654       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3655     }
3656     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3657       assert(Chunk.Kind == DeclaratorChunk::Function);
3658       TL.setLocalRangeBegin(Chunk.Loc);
3659       TL.setLocalRangeEnd(Chunk.EndLoc);
3660 
3661       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3662       TL.setLParenLoc(FTI.getLParenLoc());
3663       TL.setRParenLoc(FTI.getRParenLoc());
3664       for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
3665         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
3666         TL.setArg(tpi++, Param);
3667       }
3668       // FIXME: exception specs
3669     }
3670     void VisitParenTypeLoc(ParenTypeLoc TL) {
3671       assert(Chunk.Kind == DeclaratorChunk::Paren);
3672       TL.setLParenLoc(Chunk.Loc);
3673       TL.setRParenLoc(Chunk.EndLoc);
3674     }
3675 
3676     void VisitTypeLoc(TypeLoc TL) {
3677       llvm_unreachable("unsupported TypeLoc kind in declarator!");
3678     }
3679   };
3680 }
3681 
3682 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
3683   SourceLocation Loc;
3684   switch (Chunk.Kind) {
3685   case DeclaratorChunk::Function:
3686   case DeclaratorChunk::Array:
3687   case DeclaratorChunk::Paren:
3688     llvm_unreachable("cannot be _Atomic qualified");
3689 
3690   case DeclaratorChunk::Pointer:
3691     Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
3692     break;
3693 
3694   case DeclaratorChunk::BlockPointer:
3695   case DeclaratorChunk::Reference:
3696   case DeclaratorChunk::MemberPointer:
3697     // FIXME: Provide a source location for the _Atomic keyword.
3698     break;
3699   }
3700 
3701   ATL.setKWLoc(Loc);
3702   ATL.setParensRange(SourceRange());
3703 }
3704 
3705 /// \brief Create and instantiate a TypeSourceInfo with type source information.
3706 ///
3707 /// \param T QualType referring to the type as written in source code.
3708 ///
3709 /// \param ReturnTypeInfo For declarators whose return type does not show
3710 /// up in the normal place in the declaration specifiers (such as a C++
3711 /// conversion function), this pointer will refer to a type source information
3712 /// for that return type.
3713 TypeSourceInfo *
3714 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3715                                      TypeSourceInfo *ReturnTypeInfo) {
3716   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3717   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3718 
3719   // Handle parameter packs whose type is a pack expansion.
3720   if (isa<PackExpansionType>(T)) {
3721     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
3722     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3723   }
3724 
3725   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3726     // An AtomicTypeLoc might be produced by an atomic qualifier in this
3727     // declarator chunk.
3728     if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
3729       fillAtomicQualLoc(ATL, D.getTypeObject(i));
3730       CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
3731     }
3732 
3733     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
3734       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3735       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3736     }
3737 
3738     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3739     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3740   }
3741 
3742   // If we have different source information for the return type, use
3743   // that.  This really only applies to C++ conversion functions.
3744   if (ReturnTypeInfo) {
3745     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3746     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3747     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3748   } else {
3749     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3750   }
3751 
3752   return TInfo;
3753 }
3754 
3755 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
3756 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3757   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3758   // and Sema during declaration parsing. Try deallocating/caching them when
3759   // it's appropriate, instead of allocating them and keeping them around.
3760   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3761                                                        TypeAlignment);
3762   new (LocT) LocInfoType(T, TInfo);
3763   assert(LocT->getTypeClass() != T->getTypeClass() &&
3764          "LocInfoType's TypeClass conflicts with an existing Type class");
3765   return ParsedType::make(QualType(LocT, 0));
3766 }
3767 
3768 void LocInfoType::getAsStringInternal(std::string &Str,
3769                                       const PrintingPolicy &Policy) const {
3770   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3771          " was used directly instead of getting the QualType through"
3772          " GetTypeFromParser");
3773 }
3774 
3775 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3776   // C99 6.7.6: Type names have no identifier.  This is already validated by
3777   // the parser.
3778   assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
3779 
3780   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3781   QualType T = TInfo->getType();
3782   if (D.isInvalidType())
3783     return true;
3784 
3785   // Make sure there are no unused decl attributes on the declarator.
3786   // We don't want to do this for ObjC parameters because we're going
3787   // to apply them to the actual parameter declaration.
3788   // Likewise, we don't want to do this for alias declarations, because
3789   // we are actually going to build a declaration from this eventually.
3790   if (D.getContext() != Declarator::ObjCParameterContext &&
3791       D.getContext() != Declarator::AliasDeclContext &&
3792       D.getContext() != Declarator::AliasTemplateContext)
3793     checkUnusedDeclAttributes(D);
3794 
3795   if (getLangOpts().CPlusPlus) {
3796     // Check that there are no default arguments (C++ only).
3797     CheckExtraCXXDefaultArguments(D);
3798   }
3799 
3800   return CreateParsedType(T, TInfo);
3801 }
3802 
3803 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3804   QualType T = Context.getObjCInstanceType();
3805   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3806   return CreateParsedType(T, TInfo);
3807 }
3808 
3809 
3810 //===----------------------------------------------------------------------===//
3811 // Type Attribute Processing
3812 //===----------------------------------------------------------------------===//
3813 
3814 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3815 /// specified type.  The attribute contains 1 argument, the id of the address
3816 /// space for the type.
3817 static void HandleAddressSpaceTypeAttribute(QualType &Type,
3818                                             const AttributeList &Attr, Sema &S){
3819 
3820   // If this type is already address space qualified, reject it.
3821   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3822   // qualifiers for two or more different address spaces."
3823   if (Type.getAddressSpace()) {
3824     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3825     Attr.setInvalid();
3826     return;
3827   }
3828 
3829   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3830   // qualified by an address-space qualifier."
3831   if (Type->isFunctionType()) {
3832     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3833     Attr.setInvalid();
3834     return;
3835   }
3836 
3837   // Check the attribute arguments.
3838   if (Attr.getNumArgs() != 1) {
3839     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3840     Attr.setInvalid();
3841     return;
3842   }
3843   Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3844   llvm::APSInt addrSpace(32);
3845   if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3846       !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3847     S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3848       << ASArgExpr->getSourceRange();
3849     Attr.setInvalid();
3850     return;
3851   }
3852 
3853   // Bounds checking.
3854   if (addrSpace.isSigned()) {
3855     if (addrSpace.isNegative()) {
3856       S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3857         << ASArgExpr->getSourceRange();
3858       Attr.setInvalid();
3859       return;
3860     }
3861     addrSpace.setIsSigned(false);
3862   }
3863   llvm::APSInt max(addrSpace.getBitWidth());
3864   max = Qualifiers::MaxAddressSpace;
3865   if (addrSpace > max) {
3866     S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3867       << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
3868     Attr.setInvalid();
3869     return;
3870   }
3871 
3872   unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3873   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3874 }
3875 
3876 /// Does this type have a "direct" ownership qualifier?  That is,
3877 /// is it written like "__strong id", as opposed to something like
3878 /// "typeof(foo)", where that happens to be strong?
3879 static bool hasDirectOwnershipQualifier(QualType type) {
3880   // Fast path: no qualifier at all.
3881   assert(type.getQualifiers().hasObjCLifetime());
3882 
3883   while (true) {
3884     // __strong id
3885     if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3886       if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
3887         return true;
3888 
3889       type = attr->getModifiedType();
3890 
3891     // X *__strong (...)
3892     } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
3893       type = paren->getInnerType();
3894 
3895     // That's it for things we want to complain about.  In particular,
3896     // we do not want to look through typedefs, typeof(expr),
3897     // typeof(type), or any other way that the type is somehow
3898     // abstracted.
3899     } else {
3900 
3901       return false;
3902     }
3903   }
3904 }
3905 
3906 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
3907 /// attribute on the specified type.
3908 ///
3909 /// Returns 'true' if the attribute was handled.
3910 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
3911                                        AttributeList &attr,
3912                                        QualType &type) {
3913   bool NonObjCPointer = false;
3914 
3915   if (!type->isDependentType() && !type->isUndeducedType()) {
3916     if (const PointerType *ptr = type->getAs<PointerType>()) {
3917       QualType pointee = ptr->getPointeeType();
3918       if (pointee->isObjCRetainableType() || pointee->isPointerType())
3919         return false;
3920       // It is important not to lose the source info that there was an attribute
3921       // applied to non-objc pointer. We will create an attributed type but
3922       // its type will be the same as the original type.
3923       NonObjCPointer = true;
3924     } else if (!type->isObjCRetainableType()) {
3925       return false;
3926     }
3927 
3928     // Don't accept an ownership attribute in the declspec if it would
3929     // just be the return type of a block pointer.
3930     if (state.isProcessingDeclSpec()) {
3931       Declarator &D = state.getDeclarator();
3932       if (maybeMovePastReturnType(D, D.getNumTypeObjects()))
3933         return false;
3934     }
3935   }
3936 
3937   Sema &S = state.getSema();
3938   SourceLocation AttrLoc = attr.getLoc();
3939   if (AttrLoc.isMacroID())
3940     AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
3941 
3942   if (!attr.getParameterName()) {
3943     S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
3944       << "objc_ownership" << 1;
3945     attr.setInvalid();
3946     return true;
3947   }
3948 
3949   // Consume lifetime attributes without further comment outside of
3950   // ARC mode.
3951   if (!S.getLangOpts().ObjCAutoRefCount)
3952     return true;
3953 
3954   Qualifiers::ObjCLifetime lifetime;
3955   if (attr.getParameterName()->isStr("none"))
3956     lifetime = Qualifiers::OCL_ExplicitNone;
3957   else if (attr.getParameterName()->isStr("strong"))
3958     lifetime = Qualifiers::OCL_Strong;
3959   else if (attr.getParameterName()->isStr("weak"))
3960     lifetime = Qualifiers::OCL_Weak;
3961   else if (attr.getParameterName()->isStr("autoreleasing"))
3962     lifetime = Qualifiers::OCL_Autoreleasing;
3963   else {
3964     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
3965       << "objc_ownership" << attr.getParameterName();
3966     attr.setInvalid();
3967     return true;
3968   }
3969 
3970   SplitQualType underlyingType = type.split();
3971 
3972   // Check for redundant/conflicting ownership qualifiers.
3973   if (Qualifiers::ObjCLifetime previousLifetime
3974         = type.getQualifiers().getObjCLifetime()) {
3975     // If it's written directly, that's an error.
3976     if (hasDirectOwnershipQualifier(type)) {
3977       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3978         << type;
3979       return true;
3980     }
3981 
3982     // Otherwise, if the qualifiers actually conflict, pull sugar off
3983     // until we reach a type that is directly qualified.
3984     if (previousLifetime != lifetime) {
3985       // This should always terminate: the canonical type is
3986       // qualified, so some bit of sugar must be hiding it.
3987       while (!underlyingType.Quals.hasObjCLifetime()) {
3988         underlyingType = underlyingType.getSingleStepDesugaredType();
3989       }
3990       underlyingType.Quals.removeObjCLifetime();
3991     }
3992   }
3993 
3994   underlyingType.Quals.addObjCLifetime(lifetime);
3995 
3996   if (NonObjCPointer) {
3997     StringRef name = attr.getName()->getName();
3998     switch (lifetime) {
3999     case Qualifiers::OCL_None:
4000     case Qualifiers::OCL_ExplicitNone:
4001       break;
4002     case Qualifiers::OCL_Strong: name = "__strong"; break;
4003     case Qualifiers::OCL_Weak: name = "__weak"; break;
4004     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
4005     }
4006     S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
4007       << name << type;
4008   }
4009 
4010   QualType origType = type;
4011   if (!NonObjCPointer)
4012     type = S.Context.getQualifiedType(underlyingType);
4013 
4014   // If we have a valid source location for the attribute, use an
4015   // AttributedType instead.
4016   if (AttrLoc.isValid())
4017     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
4018                                        origType, type);
4019 
4020   // Forbid __weak if the runtime doesn't support it.
4021   if (lifetime == Qualifiers::OCL_Weak &&
4022       !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
4023 
4024     // Actually, delay this until we know what we're parsing.
4025     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
4026       S.DelayedDiagnostics.add(
4027           sema::DelayedDiagnostic::makeForbiddenType(
4028               S.getSourceManager().getExpansionLoc(AttrLoc),
4029               diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
4030     } else {
4031       S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
4032     }
4033 
4034     attr.setInvalid();
4035     return true;
4036   }
4037 
4038   // Forbid __weak for class objects marked as
4039   // objc_arc_weak_reference_unavailable
4040   if (lifetime == Qualifiers::OCL_Weak) {
4041     if (const ObjCObjectPointerType *ObjT =
4042           type->getAs<ObjCObjectPointerType>()) {
4043       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
4044         if (Class->isArcWeakrefUnavailable()) {
4045             S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
4046             S.Diag(ObjT->getInterfaceDecl()->getLocation(),
4047                    diag::note_class_declared);
4048         }
4049       }
4050     }
4051   }
4052 
4053   return true;
4054 }
4055 
4056 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
4057 /// attribute on the specified type.  Returns true to indicate that
4058 /// the attribute was handled, false to indicate that the type does
4059 /// not permit the attribute.
4060 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
4061                                  AttributeList &attr,
4062                                  QualType &type) {
4063   Sema &S = state.getSema();
4064 
4065   // Delay if this isn't some kind of pointer.
4066   if (!type->isPointerType() &&
4067       !type->isObjCObjectPointerType() &&
4068       !type->isBlockPointerType())
4069     return false;
4070 
4071   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
4072     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
4073     attr.setInvalid();
4074     return true;
4075   }
4076 
4077   // Check the attribute arguments.
4078   if (!attr.getParameterName()) {
4079     S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
4080       << "objc_gc" << 1;
4081     attr.setInvalid();
4082     return true;
4083   }
4084   Qualifiers::GC GCAttr;
4085   if (attr.getNumArgs() != 0) {
4086     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4087     attr.setInvalid();
4088     return true;
4089   }
4090   if (attr.getParameterName()->isStr("weak"))
4091     GCAttr = Qualifiers::Weak;
4092   else if (attr.getParameterName()->isStr("strong"))
4093     GCAttr = Qualifiers::Strong;
4094   else {
4095     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
4096       << "objc_gc" << attr.getParameterName();
4097     attr.setInvalid();
4098     return true;
4099   }
4100 
4101   QualType origType = type;
4102   type = S.Context.getObjCGCQualType(origType, GCAttr);
4103 
4104   // Make an attributed type to preserve the source information.
4105   if (attr.getLoc().isValid())
4106     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
4107                                        origType, type);
4108 
4109   return true;
4110 }
4111 
4112 namespace {
4113   /// A helper class to unwrap a type down to a function for the
4114   /// purposes of applying attributes there.
4115   ///
4116   /// Use:
4117   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
4118   ///   if (unwrapped.isFunctionType()) {
4119   ///     const FunctionType *fn = unwrapped.get();
4120   ///     // change fn somehow
4121   ///     T = unwrapped.wrap(fn);
4122   ///   }
4123   struct FunctionTypeUnwrapper {
4124     enum WrapKind {
4125       Desugar,
4126       Parens,
4127       Pointer,
4128       BlockPointer,
4129       Reference,
4130       MemberPointer
4131     };
4132 
4133     QualType Original;
4134     const FunctionType *Fn;
4135     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
4136 
4137     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
4138       while (true) {
4139         const Type *Ty = T.getTypePtr();
4140         if (isa<FunctionType>(Ty)) {
4141           Fn = cast<FunctionType>(Ty);
4142           return;
4143         } else if (isa<ParenType>(Ty)) {
4144           T = cast<ParenType>(Ty)->getInnerType();
4145           Stack.push_back(Parens);
4146         } else if (isa<PointerType>(Ty)) {
4147           T = cast<PointerType>(Ty)->getPointeeType();
4148           Stack.push_back(Pointer);
4149         } else if (isa<BlockPointerType>(Ty)) {
4150           T = cast<BlockPointerType>(Ty)->getPointeeType();
4151           Stack.push_back(BlockPointer);
4152         } else if (isa<MemberPointerType>(Ty)) {
4153           T = cast<MemberPointerType>(Ty)->getPointeeType();
4154           Stack.push_back(MemberPointer);
4155         } else if (isa<ReferenceType>(Ty)) {
4156           T = cast<ReferenceType>(Ty)->getPointeeType();
4157           Stack.push_back(Reference);
4158         } else {
4159           const Type *DTy = Ty->getUnqualifiedDesugaredType();
4160           if (Ty == DTy) {
4161             Fn = 0;
4162             return;
4163           }
4164 
4165           T = QualType(DTy, 0);
4166           Stack.push_back(Desugar);
4167         }
4168       }
4169     }
4170 
4171     bool isFunctionType() const { return (Fn != 0); }
4172     const FunctionType *get() const { return Fn; }
4173 
4174     QualType wrap(Sema &S, const FunctionType *New) {
4175       // If T wasn't modified from the unwrapped type, do nothing.
4176       if (New == get()) return Original;
4177 
4178       Fn = New;
4179       return wrap(S.Context, Original, 0);
4180     }
4181 
4182   private:
4183     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
4184       if (I == Stack.size())
4185         return C.getQualifiedType(Fn, Old.getQualifiers());
4186 
4187       // Build up the inner type, applying the qualifiers from the old
4188       // type to the new type.
4189       SplitQualType SplitOld = Old.split();
4190 
4191       // As a special case, tail-recurse if there are no qualifiers.
4192       if (SplitOld.Quals.empty())
4193         return wrap(C, SplitOld.Ty, I);
4194       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
4195     }
4196 
4197     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
4198       if (I == Stack.size()) return QualType(Fn, 0);
4199 
4200       switch (static_cast<WrapKind>(Stack[I++])) {
4201       case Desugar:
4202         // This is the point at which we potentially lose source
4203         // information.
4204         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
4205 
4206       case Parens: {
4207         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
4208         return C.getParenType(New);
4209       }
4210 
4211       case Pointer: {
4212         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
4213         return C.getPointerType(New);
4214       }
4215 
4216       case BlockPointer: {
4217         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
4218         return C.getBlockPointerType(New);
4219       }
4220 
4221       case MemberPointer: {
4222         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
4223         QualType New = wrap(C, OldMPT->getPointeeType(), I);
4224         return C.getMemberPointerType(New, OldMPT->getClass());
4225       }
4226 
4227       case Reference: {
4228         const ReferenceType *OldRef = cast<ReferenceType>(Old);
4229         QualType New = wrap(C, OldRef->getPointeeType(), I);
4230         if (isa<LValueReferenceType>(OldRef))
4231           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
4232         else
4233           return C.getRValueReferenceType(New);
4234       }
4235       }
4236 
4237       llvm_unreachable("unknown wrapping kind");
4238     }
4239   };
4240 }
4241 
4242 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
4243                                              AttributeList &Attr,
4244                                              QualType &Type) {
4245   Sema &S = State.getSema();
4246 
4247   AttributeList::Kind Kind = Attr.getKind();
4248   QualType Desugared = Type;
4249   const AttributedType *AT = dyn_cast<AttributedType>(Type);
4250   while (AT) {
4251     AttributedType::Kind CurAttrKind = AT->getAttrKind();
4252 
4253     // You cannot specify duplicate type attributes, so if the attribute has
4254     // already been applied, flag it.
4255     if (getAttrListKind(CurAttrKind) == Kind) {
4256       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
4257         << Attr.getName();
4258       return true;
4259     }
4260 
4261     // You cannot have both __sptr and __uptr on the same type, nor can you
4262     // have __ptr32 and __ptr64.
4263     if ((CurAttrKind == AttributedType::attr_ptr32 &&
4264          Kind == AttributeList::AT_Ptr64) ||
4265         (CurAttrKind == AttributedType::attr_ptr64 &&
4266          Kind == AttributeList::AT_Ptr32)) {
4267       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4268         << "'__ptr32'" << "'__ptr64'";
4269       return true;
4270     } else if ((CurAttrKind == AttributedType::attr_sptr &&
4271                 Kind == AttributeList::AT_UPtr) ||
4272                (CurAttrKind == AttributedType::attr_uptr &&
4273                 Kind == AttributeList::AT_SPtr)) {
4274       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4275         << "'__sptr'" << "'__uptr'";
4276       return true;
4277     }
4278 
4279     Desugared = AT->getEquivalentType();
4280     AT = dyn_cast<AttributedType>(Desugared);
4281   }
4282 
4283   // Pointer type qualifiers can only operate on pointer types, but not
4284   // pointer-to-member types.
4285   if (!isa<PointerType>(Desugared)) {
4286     S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
4287                           diag::err_attribute_no_member_pointers :
4288                           diag::err_attribute_pointers_only) << Attr.getName();
4289     return true;
4290   }
4291 
4292   AttributedType::Kind TAK;
4293   switch (Kind) {
4294   default: llvm_unreachable("Unknown attribute kind");
4295   case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
4296   case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
4297   case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
4298   case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
4299   }
4300 
4301   Type = S.Context.getAttributedType(TAK, Type, Type);
4302   return false;
4303 }
4304 
4305 /// Process an individual function attribute.  Returns true to
4306 /// indicate that the attribute was handled, false if it wasn't.
4307 static bool handleFunctionTypeAttr(TypeProcessingState &state,
4308                                    AttributeList &attr,
4309                                    QualType &type) {
4310   Sema &S = state.getSema();
4311 
4312   FunctionTypeUnwrapper unwrapped(S, type);
4313 
4314   if (attr.getKind() == AttributeList::AT_NoReturn) {
4315     if (S.CheckNoReturnAttr(attr))
4316       return true;
4317 
4318     // Delay if this is not a function type.
4319     if (!unwrapped.isFunctionType())
4320       return false;
4321 
4322     // Otherwise we can process right away.
4323     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
4324     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4325     return true;
4326   }
4327 
4328   // ns_returns_retained is not always a type attribute, but if we got
4329   // here, we're treating it as one right now.
4330   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
4331     assert(S.getLangOpts().ObjCAutoRefCount &&
4332            "ns_returns_retained treated as type attribute in non-ARC");
4333     if (attr.getNumArgs()) return true;
4334 
4335     // Delay if this is not a function type.
4336     if (!unwrapped.isFunctionType())
4337       return false;
4338 
4339     FunctionType::ExtInfo EI
4340       = unwrapped.get()->getExtInfo().withProducesResult(true);
4341     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4342     return true;
4343   }
4344 
4345   if (attr.getKind() == AttributeList::AT_Regparm) {
4346     unsigned value;
4347     if (S.CheckRegparmAttr(attr, value))
4348       return true;
4349 
4350     // Delay if this is not a function type.
4351     if (!unwrapped.isFunctionType())
4352       return false;
4353 
4354     // Diagnose regparm with fastcall.
4355     const FunctionType *fn = unwrapped.get();
4356     CallingConv CC = fn->getCallConv();
4357     if (CC == CC_X86FastCall) {
4358       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4359         << FunctionType::getNameForCallConv(CC)
4360         << "regparm";
4361       attr.setInvalid();
4362       return true;
4363     }
4364 
4365     FunctionType::ExtInfo EI =
4366       unwrapped.get()->getExtInfo().withRegParm(value);
4367     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4368     return true;
4369   }
4370 
4371   // Delay if the type didn't work out to a function.
4372   if (!unwrapped.isFunctionType()) return false;
4373 
4374   // Otherwise, a calling convention.
4375   CallingConv CC;
4376   if (S.CheckCallingConvAttr(attr, CC))
4377     return true;
4378 
4379   const FunctionType *fn = unwrapped.get();
4380   CallingConv CCOld = fn->getCallConv();
4381   if (S.Context.getCanonicalCallConv(CC) ==
4382       S.Context.getCanonicalCallConv(CCOld)) {
4383     FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
4384     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4385     return true;
4386   }
4387 
4388   if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
4389     // Should we diagnose reapplications of the same convention?
4390     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4391       << FunctionType::getNameForCallConv(CC)
4392       << FunctionType::getNameForCallConv(CCOld);
4393     attr.setInvalid();
4394     return true;
4395   }
4396 
4397   // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
4398   if (CC == CC_X86FastCall) {
4399     if (isa<FunctionNoProtoType>(fn)) {
4400       S.Diag(attr.getLoc(), diag::err_cconv_knr)
4401         << FunctionType::getNameForCallConv(CC);
4402       attr.setInvalid();
4403       return true;
4404     }
4405 
4406     const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
4407     if (FnP->isVariadic()) {
4408       S.Diag(attr.getLoc(), diag::err_cconv_varargs)
4409         << FunctionType::getNameForCallConv(CC);
4410       attr.setInvalid();
4411       return true;
4412     }
4413 
4414     // Also diagnose fastcall with regparm.
4415     if (fn->getHasRegParm()) {
4416       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4417         << "regparm"
4418         << FunctionType::getNameForCallConv(CC);
4419       attr.setInvalid();
4420       return true;
4421     }
4422   }
4423 
4424   FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
4425   type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4426   return true;
4427 }
4428 
4429 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
4430 static void HandleOpenCLImageAccessAttribute(QualType& CurType,
4431                                              const AttributeList &Attr,
4432                                              Sema &S) {
4433   // Check the attribute arguments.
4434   if (Attr.getNumArgs() != 1) {
4435     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4436     Attr.setInvalid();
4437     return;
4438   }
4439   Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
4440   llvm::APSInt arg(32);
4441   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4442       !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
4443     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4444       << "opencl_image_access" << sizeExpr->getSourceRange();
4445     Attr.setInvalid();
4446     return;
4447   }
4448   unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
4449   switch (iarg) {
4450   case CLIA_read_only:
4451   case CLIA_write_only:
4452   case CLIA_read_write:
4453     // Implemented in a separate patch
4454     break;
4455   default:
4456     // Implemented in a separate patch
4457     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4458       << sizeExpr->getSourceRange();
4459     Attr.setInvalid();
4460     break;
4461   }
4462 }
4463 
4464 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
4465 /// and float scalars, although arrays, pointers, and function return values are
4466 /// allowed in conjunction with this construct. Aggregates with this attribute
4467 /// are invalid, even if they are of the same size as a corresponding scalar.
4468 /// The raw attribute should contain precisely 1 argument, the vector size for
4469 /// the variable, measured in bytes. If curType and rawAttr are well formed,
4470 /// this routine will return a new vector type.
4471 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
4472                                  Sema &S) {
4473   // Check the attribute arguments.
4474   if (Attr.getNumArgs() != 1) {
4475     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4476     Attr.setInvalid();
4477     return;
4478   }
4479   Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
4480   llvm::APSInt vecSize(32);
4481   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4482       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
4483     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4484       << "vector_size" << sizeExpr->getSourceRange();
4485     Attr.setInvalid();
4486     return;
4487   }
4488   // the base type must be integer or float, and can't already be a vector.
4489   if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
4490     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4491     Attr.setInvalid();
4492     return;
4493   }
4494   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4495   // vecSize is specified in bytes - convert to bits.
4496   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4497 
4498   // the vector size needs to be an integral multiple of the type size.
4499   if (vectorSize % typeSize) {
4500     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4501       << sizeExpr->getSourceRange();
4502     Attr.setInvalid();
4503     return;
4504   }
4505   if (vectorSize == 0) {
4506     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4507       << sizeExpr->getSourceRange();
4508     Attr.setInvalid();
4509     return;
4510   }
4511 
4512   // Success! Instantiate the vector type, the number of elements is > 0, and
4513   // not required to be a power of 2, unlike GCC.
4514   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
4515                                     VectorType::GenericVector);
4516 }
4517 
4518 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4519 /// a type.
4520 static void HandleExtVectorTypeAttr(QualType &CurType,
4521                                     const AttributeList &Attr,
4522                                     Sema &S) {
4523   Expr *sizeExpr;
4524 
4525   // Special case where the argument is a template id.
4526   if (Attr.getParameterName()) {
4527     CXXScopeSpec SS;
4528     SourceLocation TemplateKWLoc;
4529     UnqualifiedId id;
4530     id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
4531 
4532     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4533                                           id, false, false);
4534     if (Size.isInvalid())
4535       return;
4536 
4537     sizeExpr = Size.get();
4538   } else {
4539     // check the attribute arguments.
4540     if (Attr.getNumArgs() != 1) {
4541       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4542       return;
4543     }
4544     sizeExpr = Attr.getArg(0);
4545   }
4546 
4547   // Create the vector type.
4548   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4549   if (!T.isNull())
4550     CurType = T;
4551 }
4552 
4553 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4554 /// "neon_polyvector_type" attributes are used to create vector types that
4555 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
4556 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
4557 /// the argument to these Neon attributes is the number of vector elements,
4558 /// not the vector size in bytes.  The vector width and element type must
4559 /// match one of the standard Neon vector types.
4560 static void HandleNeonVectorTypeAttr(QualType& CurType,
4561                                      const AttributeList &Attr, Sema &S,
4562                                      VectorType::VectorKind VecKind,
4563                                      const char *AttrName) {
4564   // Check the attribute arguments.
4565   if (Attr.getNumArgs() != 1) {
4566     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4567     Attr.setInvalid();
4568     return;
4569   }
4570   // The number of elements must be an ICE.
4571   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
4572   llvm::APSInt numEltsInt(32);
4573   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4574       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4575     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4576       << AttrName << numEltsExpr->getSourceRange();
4577     Attr.setInvalid();
4578     return;
4579   }
4580   // Only certain element types are supported for Neon vectors.
4581   const BuiltinType* BTy = CurType->getAs<BuiltinType>();
4582   if (!BTy ||
4583       (VecKind == VectorType::NeonPolyVector &&
4584        BTy->getKind() != BuiltinType::SChar &&
4585        BTy->getKind() != BuiltinType::Short) ||
4586       (BTy->getKind() != BuiltinType::SChar &&
4587        BTy->getKind() != BuiltinType::UChar &&
4588        BTy->getKind() != BuiltinType::Short &&
4589        BTy->getKind() != BuiltinType::UShort &&
4590        BTy->getKind() != BuiltinType::Int &&
4591        BTy->getKind() != BuiltinType::UInt &&
4592        BTy->getKind() != BuiltinType::LongLong &&
4593        BTy->getKind() != BuiltinType::ULongLong &&
4594        BTy->getKind() != BuiltinType::Float)) {
4595     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
4596     Attr.setInvalid();
4597     return;
4598   }
4599   // The total size of the vector must be 64 or 128 bits.
4600   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4601   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4602   unsigned vecSize = typeSize * numElts;
4603   if (vecSize != 64 && vecSize != 128) {
4604     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4605     Attr.setInvalid();
4606     return;
4607   }
4608 
4609   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4610 }
4611 
4612 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
4613                              TypeAttrLocation TAL, AttributeList *attrs) {
4614   // Scan through and apply attributes to this type where it makes sense.  Some
4615   // attributes (such as __address_space__, __vector_size__, etc) apply to the
4616   // type, but others can be present in the type specifiers even though they
4617   // apply to the decl.  Here we apply type attributes and ignore the rest.
4618 
4619   AttributeList *next;
4620   do {
4621     AttributeList &attr = *attrs;
4622     next = attr.getNext();
4623 
4624     // Skip attributes that were marked to be invalid.
4625     if (attr.isInvalid())
4626       continue;
4627 
4628     if (attr.isCXX11Attribute()) {
4629       // [[gnu::...]] attributes are treated as declaration attributes, so may
4630       // not appertain to a DeclaratorChunk, even if we handle them as type
4631       // attributes.
4632       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
4633         if (TAL == TAL_DeclChunk) {
4634           state.getSema().Diag(attr.getLoc(),
4635                                diag::warn_cxx11_gnu_attribute_on_type)
4636               << attr.getName();
4637           continue;
4638         }
4639       } else if (TAL != TAL_DeclChunk) {
4640         // Otherwise, only consider type processing for a C++11 attribute if
4641         // it's actually been applied to a type.
4642         continue;
4643       }
4644     }
4645 
4646     // If this is an attribute we can handle, do so now,
4647     // otherwise, add it to the FnAttrs list for rechaining.
4648     switch (attr.getKind()) {
4649     default:
4650       // A C++11 attribute on a declarator chunk must appertain to a type.
4651       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
4652         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
4653           << attr.getName();
4654         attr.setUsedAsTypeAttr();
4655       }
4656       break;
4657 
4658     case AttributeList::UnknownAttribute:
4659       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4660         state.getSema().Diag(attr.getLoc(),
4661                              diag::warn_unknown_attribute_ignored)
4662           << attr.getName();
4663       break;
4664 
4665     case AttributeList::IgnoredAttribute:
4666       break;
4667 
4668     case AttributeList::AT_MayAlias:
4669       // FIXME: This attribute needs to actually be handled, but if we ignore
4670       // it it breaks large amounts of Linux software.
4671       attr.setUsedAsTypeAttr();
4672       break;
4673     case AttributeList::AT_AddressSpace:
4674       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
4675       attr.setUsedAsTypeAttr();
4676       break;
4677     OBJC_POINTER_TYPE_ATTRS_CASELIST:
4678       if (!handleObjCPointerTypeAttr(state, attr, type))
4679         distributeObjCPointerTypeAttr(state, attr, type);
4680       attr.setUsedAsTypeAttr();
4681       break;
4682     case AttributeList::AT_VectorSize:
4683       HandleVectorSizeAttr(type, attr, state.getSema());
4684       attr.setUsedAsTypeAttr();
4685       break;
4686     case AttributeList::AT_ExtVectorType:
4687       HandleExtVectorTypeAttr(type, attr, state.getSema());
4688       attr.setUsedAsTypeAttr();
4689       break;
4690     case AttributeList::AT_NeonVectorType:
4691       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4692                                VectorType::NeonVector, "neon_vector_type");
4693       attr.setUsedAsTypeAttr();
4694       break;
4695     case AttributeList::AT_NeonPolyVectorType:
4696       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4697                                VectorType::NeonPolyVector,
4698                                "neon_polyvector_type");
4699       attr.setUsedAsTypeAttr();
4700       break;
4701     case AttributeList::AT_OpenCLImageAccess:
4702       HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
4703       attr.setUsedAsTypeAttr();
4704       break;
4705 
4706     case AttributeList::AT_Win64:
4707       attr.setUsedAsTypeAttr();
4708       break;
4709     MS_TYPE_ATTRS_CASELIST:
4710       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
4711         attr.setUsedAsTypeAttr();
4712       break;
4713 
4714     case AttributeList::AT_NSReturnsRetained:
4715       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
4716         break;
4717       // fallthrough into the function attrs
4718 
4719     FUNCTION_TYPE_ATTRS_CASELIST:
4720       attr.setUsedAsTypeAttr();
4721 
4722       // Never process function type attributes as part of the
4723       // declaration-specifiers.
4724       if (TAL == TAL_DeclSpec)
4725         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4726 
4727       // Otherwise, handle the possible delays.
4728       else if (!handleFunctionTypeAttr(state, attr, type))
4729         distributeFunctionTypeAttr(state, attr, type);
4730       break;
4731     }
4732   } while ((attrs = next));
4733 }
4734 
4735 /// \brief Ensure that the type of the given expression is complete.
4736 ///
4737 /// This routine checks whether the expression \p E has a complete type. If the
4738 /// expression refers to an instantiable construct, that instantiation is
4739 /// performed as needed to complete its type. Furthermore
4740 /// Sema::RequireCompleteType is called for the expression's type (or in the
4741 /// case of a reference type, the referred-to type).
4742 ///
4743 /// \param E The expression whose type is required to be complete.
4744 /// \param Diagnoser The object that will emit a diagnostic if the type is
4745 /// incomplete.
4746 ///
4747 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4748 /// otherwise.
4749 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
4750   QualType T = E->getType();
4751 
4752   // Fast path the case where the type is already complete.
4753   if (!T->isIncompleteType())
4754     return false;
4755 
4756   // Incomplete array types may be completed by the initializer attached to
4757   // their definitions. For static data members of class templates we need to
4758   // instantiate the definition to get this initializer and complete the type.
4759   if (T->isIncompleteArrayType()) {
4760     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4761       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4762         if (Var->isStaticDataMember() &&
4763             Var->getInstantiatedFromStaticDataMember()) {
4764 
4765           MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4766           assert(MSInfo && "Missing member specialization information?");
4767           if (MSInfo->getTemplateSpecializationKind()
4768                 != TSK_ExplicitSpecialization) {
4769             // If we don't already have a point of instantiation, this is it.
4770             if (MSInfo->getPointOfInstantiation().isInvalid()) {
4771               MSInfo->setPointOfInstantiation(E->getLocStart());
4772 
4773               // This is a modification of an existing AST node. Notify
4774               // listeners.
4775               if (ASTMutationListener *L = getASTMutationListener())
4776                 L->StaticDataMemberInstantiated(Var);
4777             }
4778 
4779             InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
4780 
4781             // Update the type to the newly instantiated definition's type both
4782             // here and within the expression.
4783             if (VarDecl *Def = Var->getDefinition()) {
4784               DRE->setDecl(Def);
4785               T = Def->getType();
4786               DRE->setType(T);
4787               E->setType(T);
4788             }
4789           }
4790 
4791           // We still go on to try to complete the type independently, as it
4792           // may also require instantiations or diagnostics if it remains
4793           // incomplete.
4794         }
4795       }
4796     }
4797   }
4798 
4799   // FIXME: Are there other cases which require instantiating something other
4800   // than the type to complete the type of an expression?
4801 
4802   // Look through reference types and complete the referred type.
4803   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4804     T = Ref->getPointeeType();
4805 
4806   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
4807 }
4808 
4809 namespace {
4810   struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
4811     unsigned DiagID;
4812 
4813     TypeDiagnoserDiag(unsigned DiagID)
4814       : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
4815 
4816     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
4817       if (Suppressed) return;
4818       S.Diag(Loc, DiagID) << T;
4819     }
4820   };
4821 }
4822 
4823 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
4824   TypeDiagnoserDiag Diagnoser(DiagID);
4825   return RequireCompleteExprType(E, Diagnoser);
4826 }
4827 
4828 /// @brief Ensure that the type T is a complete type.
4829 ///
4830 /// This routine checks whether the type @p T is complete in any
4831 /// context where a complete type is required. If @p T is a complete
4832 /// type, returns false. If @p T is a class template specialization,
4833 /// this routine then attempts to perform class template
4834 /// instantiation. If instantiation fails, or if @p T is incomplete
4835 /// and cannot be completed, issues the diagnostic @p diag (giving it
4836 /// the type @p T) and returns true.
4837 ///
4838 /// @param Loc  The location in the source that the incomplete type
4839 /// diagnostic should refer to.
4840 ///
4841 /// @param T  The type that this routine is examining for completeness.
4842 ///
4843 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4844 /// @c false otherwise.
4845 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4846                                TypeDiagnoser &Diagnoser) {
4847   // FIXME: Add this assertion to make sure we always get instantiation points.
4848   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
4849   // FIXME: Add this assertion to help us flush out problems with
4850   // checking for dependent types and type-dependent expressions.
4851   //
4852   //  assert(!T->isDependentType() &&
4853   //         "Can't ask whether a dependent type is complete");
4854 
4855   // If we have a complete type, we're done.
4856   NamedDecl *Def = 0;
4857   if (!T->isIncompleteType(&Def)) {
4858     // If we know about the definition but it is not visible, complain.
4859     if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) {
4860       // Suppress this error outside of a SFINAE context if we've already
4861       // emitted the error once for this type. There's no usefulness in
4862       // repeating the diagnostic.
4863       // FIXME: Add a Fix-It that imports the corresponding module or includes
4864       // the header.
4865       Module *Owner = Def->getOwningModule();
4866       Diag(Loc, diag::err_module_private_definition)
4867         << T << Owner->getFullModuleName();
4868       Diag(Def->getLocation(), diag::note_previous_definition);
4869 
4870       if (!isSFINAEContext()) {
4871         // Recover by implicitly importing this module.
4872         createImplicitModuleImport(Loc, Owner);
4873       }
4874     }
4875 
4876     return false;
4877   }
4878 
4879   const TagType *Tag = T->getAs<TagType>();
4880   const ObjCInterfaceType *IFace = 0;
4881 
4882   if (Tag) {
4883     // Avoid diagnosing invalid decls as incomplete.
4884     if (Tag->getDecl()->isInvalidDecl())
4885       return true;
4886 
4887     // Give the external AST source a chance to complete the type.
4888     if (Tag->getDecl()->hasExternalLexicalStorage()) {
4889       Context.getExternalSource()->CompleteType(Tag->getDecl());
4890       if (!Tag->isIncompleteType())
4891         return false;
4892     }
4893   }
4894   else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4895     // Avoid diagnosing invalid decls as incomplete.
4896     if (IFace->getDecl()->isInvalidDecl())
4897       return true;
4898 
4899     // Give the external AST source a chance to complete the type.
4900     if (IFace->getDecl()->hasExternalLexicalStorage()) {
4901       Context.getExternalSource()->CompleteType(IFace->getDecl());
4902       if (!IFace->isIncompleteType())
4903         return false;
4904     }
4905   }
4906 
4907   // If we have a class template specialization or a class member of a
4908   // class template specialization, or an array with known size of such,
4909   // try to instantiate it.
4910   QualType MaybeTemplate = T;
4911   while (const ConstantArrayType *Array
4912            = Context.getAsConstantArrayType(MaybeTemplate))
4913     MaybeTemplate = Array->getElementType();
4914   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
4915     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
4916           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
4917       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4918         return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
4919                                                       TSK_ImplicitInstantiation,
4920                                             /*Complain=*/!Diagnoser.Suppressed);
4921     } else if (CXXRecordDecl *Rec
4922                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
4923       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
4924       if (!Rec->isBeingDefined() && Pattern) {
4925         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
4926         assert(MSI && "Missing member specialization information?");
4927         // This record was instantiated from a class within a template.
4928         if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
4929           return InstantiateClass(Loc, Rec, Pattern,
4930                                   getTemplateInstantiationArgs(Rec),
4931                                   TSK_ImplicitInstantiation,
4932                                   /*Complain=*/!Diagnoser.Suppressed);
4933       }
4934     }
4935   }
4936 
4937   if (Diagnoser.Suppressed)
4938     return true;
4939 
4940   // We have an incomplete type. Produce a diagnostic.
4941   if (Ident___float128 &&
4942       T == Context.getTypeDeclType(Context.getFloat128StubType())) {
4943     Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
4944     return true;
4945   }
4946 
4947   Diagnoser.diagnose(*this, Loc, T);
4948 
4949   // If the type was a forward declaration of a class/struct/union
4950   // type, produce a note.
4951   if (Tag && !Tag->getDecl()->isInvalidDecl())
4952     Diag(Tag->getDecl()->getLocation(),
4953          Tag->isBeingDefined() ? diag::note_type_being_defined
4954                                : diag::note_forward_declaration)
4955       << QualType(Tag, 0);
4956 
4957   // If the Objective-C class was a forward declaration, produce a note.
4958   if (IFace && !IFace->getDecl()->isInvalidDecl())
4959     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
4960 
4961   return true;
4962 }
4963 
4964 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4965                                unsigned DiagID) {
4966   TypeDiagnoserDiag Diagnoser(DiagID);
4967   return RequireCompleteType(Loc, T, Diagnoser);
4968 }
4969 
4970 /// \brief Get diagnostic %select index for tag kind for
4971 /// literal type diagnostic message.
4972 /// WARNING: Indexes apply to particular diagnostics only!
4973 ///
4974 /// \returns diagnostic %select index.
4975 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
4976   switch (Tag) {
4977   case TTK_Struct: return 0;
4978   case TTK_Interface: return 1;
4979   case TTK_Class:  return 2;
4980   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
4981   }
4982 }
4983 
4984 /// @brief Ensure that the type T is a literal type.
4985 ///
4986 /// This routine checks whether the type @p T is a literal type. If @p T is an
4987 /// incomplete type, an attempt is made to complete it. If @p T is a literal
4988 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4989 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4990 /// it the type @p T), along with notes explaining why the type is not a
4991 /// literal type, and returns true.
4992 ///
4993 /// @param Loc  The location in the source that the non-literal type
4994 /// diagnostic should refer to.
4995 ///
4996 /// @param T  The type that this routine is examining for literalness.
4997 ///
4998 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
4999 ///
5000 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
5001 /// @c false otherwise.
5002 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
5003                               TypeDiagnoser &Diagnoser) {
5004   assert(!T->isDependentType() && "type should not be dependent");
5005 
5006   QualType ElemType = Context.getBaseElementType(T);
5007   RequireCompleteType(Loc, ElemType, 0);
5008 
5009   if (T->isLiteralType(Context))
5010     return false;
5011 
5012   if (Diagnoser.Suppressed)
5013     return true;
5014 
5015   Diagnoser.diagnose(*this, Loc, T);
5016 
5017   if (T->isVariableArrayType())
5018     return true;
5019 
5020   const RecordType *RT = ElemType->getAs<RecordType>();
5021   if (!RT)
5022     return true;
5023 
5024   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5025 
5026   // A partially-defined class type can't be a literal type, because a literal
5027   // class type must have a trivial destructor (which can't be checked until
5028   // the class definition is complete).
5029   if (!RD->isCompleteDefinition()) {
5030     RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
5031     return true;
5032   }
5033 
5034   // If the class has virtual base classes, then it's not an aggregate, and
5035   // cannot have any constexpr constructors or a trivial default constructor,
5036   // so is non-literal. This is better to diagnose than the resulting absence
5037   // of constexpr constructors.
5038   if (RD->getNumVBases()) {
5039     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
5040       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
5041     for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
5042            E = RD->vbases_end(); I != E; ++I)
5043       Diag(I->getLocStart(),
5044            diag::note_constexpr_virtual_base_here) << I->getSourceRange();
5045   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
5046              !RD->hasTrivialDefaultConstructor()) {
5047     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
5048   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
5049     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5050          E = RD->bases_end(); I != E; ++I) {
5051       if (!I->getType()->isLiteralType(Context)) {
5052         Diag(I->getLocStart(),
5053              diag::note_non_literal_base_class)
5054           << RD << I->getType() << I->getSourceRange();
5055         return true;
5056       }
5057     }
5058     for (CXXRecordDecl::field_iterator I = RD->field_begin(),
5059          E = RD->field_end(); I != E; ++I) {
5060       if (!I->getType()->isLiteralType(Context) ||
5061           I->getType().isVolatileQualified()) {
5062         Diag(I->getLocation(), diag::note_non_literal_field)
5063           << RD << *I << I->getType()
5064           << I->getType().isVolatileQualified();
5065         return true;
5066       }
5067     }
5068   } else if (!RD->hasTrivialDestructor()) {
5069     // All fields and bases are of literal types, so have trivial destructors.
5070     // If this class's destructor is non-trivial it must be user-declared.
5071     CXXDestructorDecl *Dtor = RD->getDestructor();
5072     assert(Dtor && "class has literal fields and bases but no dtor?");
5073     if (!Dtor)
5074       return true;
5075 
5076     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
5077          diag::note_non_literal_user_provided_dtor :
5078          diag::note_non_literal_nontrivial_dtor) << RD;
5079     if (!Dtor->isUserProvided())
5080       SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
5081   }
5082 
5083   return true;
5084 }
5085 
5086 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
5087   TypeDiagnoserDiag Diagnoser(DiagID);
5088   return RequireLiteralType(Loc, T, Diagnoser);
5089 }
5090 
5091 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
5092 /// and qualified by the nested-name-specifier contained in SS.
5093 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
5094                                  const CXXScopeSpec &SS, QualType T) {
5095   if (T.isNull())
5096     return T;
5097   NestedNameSpecifier *NNS;
5098   if (SS.isValid())
5099     NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5100   else {
5101     if (Keyword == ETK_None)
5102       return T;
5103     NNS = 0;
5104   }
5105   return Context.getElaboratedType(Keyword, NNS, T);
5106 }
5107 
5108 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
5109   ExprResult ER = CheckPlaceholderExpr(E);
5110   if (ER.isInvalid()) return QualType();
5111   E = ER.take();
5112 
5113   if (!E->isTypeDependent()) {
5114     QualType T = E->getType();
5115     if (const TagType *TT = T->getAs<TagType>())
5116       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
5117   }
5118   return Context.getTypeOfExprType(E);
5119 }
5120 
5121 /// getDecltypeForExpr - Given an expr, will return the decltype for
5122 /// that expression, according to the rules in C++11
5123 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
5124 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
5125   if (E->isTypeDependent())
5126     return S.Context.DependentTy;
5127 
5128   // C++11 [dcl.type.simple]p4:
5129   //   The type denoted by decltype(e) is defined as follows:
5130   //
5131   //     - if e is an unparenthesized id-expression or an unparenthesized class
5132   //       member access (5.2.5), decltype(e) is the type of the entity named
5133   //       by e. If there is no such entity, or if e names a set of overloaded
5134   //       functions, the program is ill-formed;
5135   //
5136   // We apply the same rules for Objective-C ivar and property references.
5137   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5138     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
5139       return VD->getType();
5140   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5141     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
5142       return FD->getType();
5143   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
5144     return IR->getDecl()->getType();
5145   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
5146     if (PR->isExplicitProperty())
5147       return PR->getExplicitProperty()->getType();
5148   }
5149 
5150   // C++11 [expr.lambda.prim]p18:
5151   //   Every occurrence of decltype((x)) where x is a possibly
5152   //   parenthesized id-expression that names an entity of automatic
5153   //   storage duration is treated as if x were transformed into an
5154   //   access to a corresponding data member of the closure type that
5155   //   would have been declared if x were an odr-use of the denoted
5156   //   entity.
5157   using namespace sema;
5158   if (S.getCurLambda()) {
5159     if (isa<ParenExpr>(E)) {
5160       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5161         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5162           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
5163           if (!T.isNull())
5164             return S.Context.getLValueReferenceType(T);
5165         }
5166       }
5167     }
5168   }
5169 
5170 
5171   // C++11 [dcl.type.simple]p4:
5172   //   [...]
5173   QualType T = E->getType();
5174   switch (E->getValueKind()) {
5175   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5176   //       type of e;
5177   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
5178   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5179   //       type of e;
5180   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
5181   //  - otherwise, decltype(e) is the type of e.
5182   case VK_RValue: break;
5183   }
5184 
5185   return T;
5186 }
5187 
5188 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
5189   ExprResult ER = CheckPlaceholderExpr(E);
5190   if (ER.isInvalid()) return QualType();
5191   E = ER.take();
5192 
5193   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
5194 }
5195 
5196 QualType Sema::BuildUnaryTransformType(QualType BaseType,
5197                                        UnaryTransformType::UTTKind UKind,
5198                                        SourceLocation Loc) {
5199   switch (UKind) {
5200   case UnaryTransformType::EnumUnderlyingType:
5201     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
5202       Diag(Loc, diag::err_only_enums_have_underlying_types);
5203       return QualType();
5204     } else {
5205       QualType Underlying = BaseType;
5206       if (!BaseType->isDependentType()) {
5207         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
5208         assert(ED && "EnumType has no EnumDecl");
5209         DiagnoseUseOfDecl(ED, Loc);
5210         Underlying = ED->getIntegerType();
5211       }
5212       assert(!Underlying.isNull());
5213       return Context.getUnaryTransformType(BaseType, Underlying,
5214                                         UnaryTransformType::EnumUnderlyingType);
5215     }
5216   }
5217   llvm_unreachable("unknown unary transform type");
5218 }
5219 
5220 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
5221   if (!T->isDependentType()) {
5222     // FIXME: It isn't entirely clear whether incomplete atomic types
5223     // are allowed or not; for simplicity, ban them for the moment.
5224     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
5225       return QualType();
5226 
5227     int DisallowedKind = -1;
5228     if (T->isArrayType())
5229       DisallowedKind = 1;
5230     else if (T->isFunctionType())
5231       DisallowedKind = 2;
5232     else if (T->isReferenceType())
5233       DisallowedKind = 3;
5234     else if (T->isAtomicType())
5235       DisallowedKind = 4;
5236     else if (T.hasQualifiers())
5237       DisallowedKind = 5;
5238     else if (!T.isTriviallyCopyableType(Context))
5239       // Some other non-trivially-copyable type (probably a C++ class)
5240       DisallowedKind = 6;
5241 
5242     if (DisallowedKind != -1) {
5243       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
5244       return QualType();
5245     }
5246 
5247     // FIXME: Do we need any handling for ARC here?
5248   }
5249 
5250   // Build the pointer type.
5251   return Context.getAtomicType(T);
5252 }
5253