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