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