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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/ASTStructuralEquivalence.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/Lex/Preprocessor.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/SemaInternal.h"
33 #include "clang/Sema/Template.h"
34 #include "clang/Sema/TemplateInstCallback.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/Support/ErrorHandling.h"
39 
40 using namespace clang;
41 
42 enum TypeDiagSelector {
43   TDS_Function,
44   TDS_Pointer,
45   TDS_ObjCObjOrBlock
46 };
47 
48 /// isOmittedBlockReturnType - Return true if this declarator is missing a
49 /// return type because this is a omitted return type on a block literal.
50 static bool isOmittedBlockReturnType(const Declarator &D) {
51   if (D.getContext() != DeclaratorContext::BlockLiteralContext ||
52       D.getDeclSpec().hasTypeSpecifier())
53     return false;
54 
55   if (D.getNumTypeObjects() == 0)
56     return true;   // ^{ ... }
57 
58   if (D.getNumTypeObjects() == 1 &&
59       D.getTypeObject(0).Kind == DeclaratorChunk::Function)
60     return true;   // ^(int X, float Y) { ... }
61 
62   return false;
63 }
64 
65 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
66 /// doesn't apply to the given type.
67 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
68                                      QualType type) {
69   TypeDiagSelector WhichType;
70   bool useExpansionLoc = true;
71   switch (attr.getKind()) {
72   case AttributeList::AT_ObjCGC:        WhichType = TDS_Pointer; break;
73   case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
74   default:
75     // Assume everything else was a function attribute.
76     WhichType = TDS_Function;
77     useExpansionLoc = false;
78     break;
79   }
80 
81   SourceLocation loc = attr.getLoc();
82   StringRef name = attr.getName()->getName();
83 
84   // The GC attributes are usually written with macros;  special-case them.
85   IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
86                                           : nullptr;
87   if (useExpansionLoc && loc.isMacroID() && II) {
88     if (II->isStr("strong")) {
89       if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
90     } else if (II->isStr("weak")) {
91       if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
92     }
93   }
94 
95   S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
96     << type;
97 }
98 
99 // objc_gc applies to Objective-C pointers or, otherwise, to the
100 // smallest available pointer type (i.e. 'void*' in 'void**').
101 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
102     case AttributeList::AT_ObjCGC: \
103     case AttributeList::AT_ObjCOwnership
104 
105 // Calling convention attributes.
106 #define CALLING_CONV_ATTRS_CASELIST \
107     case AttributeList::AT_CDecl: \
108     case AttributeList::AT_FastCall: \
109     case AttributeList::AT_StdCall: \
110     case AttributeList::AT_ThisCall: \
111     case AttributeList::AT_RegCall: \
112     case AttributeList::AT_Pascal: \
113     case AttributeList::AT_SwiftCall: \
114     case AttributeList::AT_VectorCall: \
115     case AttributeList::AT_MSABI: \
116     case AttributeList::AT_SysVABI: \
117     case AttributeList::AT_Pcs: \
118     case AttributeList::AT_IntelOclBicc: \
119     case AttributeList::AT_PreserveMost: \
120     case AttributeList::AT_PreserveAll
121 
122 // Function type attributes.
123 #define FUNCTION_TYPE_ATTRS_CASELIST \
124   case AttributeList::AT_NSReturnsRetained: \
125   case AttributeList::AT_NoReturn: \
126   case AttributeList::AT_Regparm: \
127   case AttributeList::AT_AnyX86NoCallerSavedRegisters: \
128   case AttributeList::AT_AnyX86NoCfCheck: \
129     CALLING_CONV_ATTRS_CASELIST
130 
131 // Microsoft-specific type qualifiers.
132 #define MS_TYPE_ATTRS_CASELIST  \
133     case AttributeList::AT_Ptr32: \
134     case AttributeList::AT_Ptr64: \
135     case AttributeList::AT_SPtr: \
136     case AttributeList::AT_UPtr
137 
138 // Nullability qualifiers.
139 #define NULLABILITY_TYPE_ATTRS_CASELIST         \
140     case AttributeList::AT_TypeNonNull:         \
141     case AttributeList::AT_TypeNullable:        \
142     case AttributeList::AT_TypeNullUnspecified
143 
144 namespace {
145   /// An object which stores processing state for the entire
146   /// GetTypeForDeclarator process.
147   class TypeProcessingState {
148     Sema &sema;
149 
150     /// The declarator being processed.
151     Declarator &declarator;
152 
153     /// The index of the declarator chunk we're currently processing.
154     /// May be the total number of valid chunks, indicating the
155     /// DeclSpec.
156     unsigned chunkIndex;
157 
158     /// Whether there are non-trivial modifications to the decl spec.
159     bool trivial;
160 
161     /// Whether we saved the attributes in the decl spec.
162     bool hasSavedAttrs;
163 
164     /// The original set of attributes on the DeclSpec.
165     SmallVector<AttributeList*, 2> savedAttrs;
166 
167     /// A list of attributes to diagnose the uselessness of when the
168     /// processing is complete.
169     SmallVector<AttributeList*, 2> ignoredTypeAttrs;
170 
171   public:
172     TypeProcessingState(Sema &sema, Declarator &declarator)
173       : sema(sema), declarator(declarator),
174         chunkIndex(declarator.getNumTypeObjects()),
175         trivial(true), hasSavedAttrs(false) {}
176 
177     Sema &getSema() const {
178       return sema;
179     }
180 
181     Declarator &getDeclarator() const {
182       return declarator;
183     }
184 
185     bool isProcessingDeclSpec() const {
186       return chunkIndex == declarator.getNumTypeObjects();
187     }
188 
189     unsigned getCurrentChunkIndex() const {
190       return chunkIndex;
191     }
192 
193     void setCurrentChunkIndex(unsigned idx) {
194       assert(idx <= declarator.getNumTypeObjects());
195       chunkIndex = idx;
196     }
197 
198     AttributeList *&getCurrentAttrListRef() const {
199       if (isProcessingDeclSpec())
200         return getMutableDeclSpec().getAttributes().getListRef();
201       return declarator.getTypeObject(chunkIndex).getAttrListRef();
202     }
203 
204     /// Save the current set of attributes on the DeclSpec.
205     void saveDeclSpecAttrs() {
206       // Don't try to save them multiple times.
207       if (hasSavedAttrs) return;
208 
209       DeclSpec &spec = getMutableDeclSpec();
210       for (AttributeList *attr = spec.getAttributes().getList(); attr;
211              attr = attr->getNext())
212         savedAttrs.push_back(attr);
213       trivial &= savedAttrs.empty();
214       hasSavedAttrs = true;
215     }
216 
217     /// Record that we had nowhere to put the given type attribute.
218     /// We will diagnose such attributes later.
219     void addIgnoredTypeAttr(AttributeList &attr) {
220       ignoredTypeAttrs.push_back(&attr);
221     }
222 
223     /// Diagnose all the ignored type attributes, given that the
224     /// declarator worked out to the given type.
225     void diagnoseIgnoredTypeAttrs(QualType type) const {
226       for (auto *Attr : ignoredTypeAttrs)
227         diagnoseBadTypeAttribute(getSema(), *Attr, type);
228     }
229 
230     ~TypeProcessingState() {
231       if (trivial) return;
232 
233       restoreDeclSpecAttrs();
234     }
235 
236   private:
237     DeclSpec &getMutableDeclSpec() const {
238       return const_cast<DeclSpec&>(declarator.getDeclSpec());
239     }
240 
241     void restoreDeclSpecAttrs() {
242       assert(hasSavedAttrs);
243 
244       if (savedAttrs.empty()) {
245         getMutableDeclSpec().getAttributes().set(nullptr);
246         return;
247       }
248 
249       getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
250       for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
251         savedAttrs[i]->setNext(savedAttrs[i+1]);
252       savedAttrs.back()->setNext(nullptr);
253     }
254   };
255 } // end anonymous namespace
256 
257 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
258   attr.setNext(head);
259   head = &attr;
260 }
261 
262 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
263   if (head == &attr) {
264     head = attr.getNext();
265     return;
266   }
267 
268   AttributeList *cur = head;
269   while (true) {
270     assert(cur && cur->getNext() && "ran out of attrs?");
271     if (cur->getNext() == &attr) {
272       cur->setNext(attr.getNext());
273       return;
274     }
275     cur = cur->getNext();
276   }
277 }
278 
279 static void moveAttrFromListToList(AttributeList &attr,
280                                    AttributeList *&fromList,
281                                    AttributeList *&toList) {
282   spliceAttrOutOfList(attr, fromList);
283   spliceAttrIntoList(attr, toList);
284 }
285 
286 /// The location of a type attribute.
287 enum TypeAttrLocation {
288   /// The attribute is in the decl-specifier-seq.
289   TAL_DeclSpec,
290   /// The attribute is part of a DeclaratorChunk.
291   TAL_DeclChunk,
292   /// The attribute is immediately after the declaration's name.
293   TAL_DeclName
294 };
295 
296 static void processTypeAttrs(TypeProcessingState &state,
297                              QualType &type, TypeAttrLocation TAL,
298                              AttributeList *attrs);
299 
300 static bool handleFunctionTypeAttr(TypeProcessingState &state,
301                                    AttributeList &attr,
302                                    QualType &type);
303 
304 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
305                                              AttributeList &attr,
306                                              QualType &type);
307 
308 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
309                                  AttributeList &attr, QualType &type);
310 
311 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
312                                        AttributeList &attr, QualType &type);
313 
314 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
315                                       AttributeList &attr, QualType &type) {
316   if (attr.getKind() == AttributeList::AT_ObjCGC)
317     return handleObjCGCTypeAttr(state, attr, type);
318   assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
319   return handleObjCOwnershipTypeAttr(state, attr, type);
320 }
321 
322 /// Given the index of a declarator chunk, check whether that chunk
323 /// directly specifies the return type of a function and, if so, find
324 /// an appropriate place for it.
325 ///
326 /// \param i - a notional index which the search will start
327 ///   immediately inside
328 ///
329 /// \param onlyBlockPointers Whether we should only look into block
330 /// pointer types (vs. all pointer types).
331 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
332                                                 unsigned i,
333                                                 bool onlyBlockPointers) {
334   assert(i <= declarator.getNumTypeObjects());
335 
336   DeclaratorChunk *result = nullptr;
337 
338   // First, look inwards past parens for a function declarator.
339   for (; i != 0; --i) {
340     DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
341     switch (fnChunk.Kind) {
342     case DeclaratorChunk::Paren:
343       continue;
344 
345     // If we find anything except a function, bail out.
346     case DeclaratorChunk::Pointer:
347     case DeclaratorChunk::BlockPointer:
348     case DeclaratorChunk::Array:
349     case DeclaratorChunk::Reference:
350     case DeclaratorChunk::MemberPointer:
351     case DeclaratorChunk::Pipe:
352       return result;
353 
354     // If we do find a function declarator, scan inwards from that,
355     // looking for a (block-)pointer declarator.
356     case DeclaratorChunk::Function:
357       for (--i; i != 0; --i) {
358         DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
359         switch (ptrChunk.Kind) {
360         case DeclaratorChunk::Paren:
361         case DeclaratorChunk::Array:
362         case DeclaratorChunk::Function:
363         case DeclaratorChunk::Reference:
364         case DeclaratorChunk::Pipe:
365           continue;
366 
367         case DeclaratorChunk::MemberPointer:
368         case DeclaratorChunk::Pointer:
369           if (onlyBlockPointers)
370             continue;
371 
372           LLVM_FALLTHROUGH;
373 
374         case DeclaratorChunk::BlockPointer:
375           result = &ptrChunk;
376           goto continue_outer;
377         }
378         llvm_unreachable("bad declarator chunk kind");
379       }
380 
381       // If we run out of declarators doing that, we're done.
382       return result;
383     }
384     llvm_unreachable("bad declarator chunk kind");
385 
386     // Okay, reconsider from our new point.
387   continue_outer: ;
388   }
389 
390   // Ran out of chunks, bail out.
391   return result;
392 }
393 
394 /// Given that an objc_gc attribute was written somewhere on a
395 /// declaration *other* than on the declarator itself (for which, use
396 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
397 /// didn't apply in whatever position it was written in, try to move
398 /// it to a more appropriate position.
399 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
400                                           AttributeList &attr,
401                                           QualType type) {
402   Declarator &declarator = state.getDeclarator();
403 
404   // Move it to the outermost normal or block pointer declarator.
405   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
406     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
407     switch (chunk.Kind) {
408     case DeclaratorChunk::Pointer:
409     case DeclaratorChunk::BlockPointer: {
410       // But don't move an ARC ownership attribute to the return type
411       // of a block.
412       DeclaratorChunk *destChunk = nullptr;
413       if (state.isProcessingDeclSpec() &&
414           attr.getKind() == AttributeList::AT_ObjCOwnership)
415         destChunk = maybeMovePastReturnType(declarator, i - 1,
416                                             /*onlyBlockPointers=*/true);
417       if (!destChunk) destChunk = &chunk;
418 
419       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
420                              destChunk->getAttrListRef());
421       return;
422     }
423 
424     case DeclaratorChunk::Paren:
425     case DeclaratorChunk::Array:
426       continue;
427 
428     // We may be starting at the return type of a block.
429     case DeclaratorChunk::Function:
430       if (state.isProcessingDeclSpec() &&
431           attr.getKind() == AttributeList::AT_ObjCOwnership) {
432         if (DeclaratorChunk *dest = maybeMovePastReturnType(
433                                       declarator, i,
434                                       /*onlyBlockPointers=*/true)) {
435           moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
436                                  dest->getAttrListRef());
437           return;
438         }
439       }
440       goto error;
441 
442     // Don't walk through these.
443     case DeclaratorChunk::Reference:
444     case DeclaratorChunk::MemberPointer:
445     case DeclaratorChunk::Pipe:
446       goto error;
447     }
448   }
449  error:
450 
451   diagnoseBadTypeAttribute(state.getSema(), attr, type);
452 }
453 
454 /// Distribute an objc_gc type attribute that was written on the
455 /// declarator.
456 static void
457 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
458                                             AttributeList &attr,
459                                             QualType &declSpecType) {
460   Declarator &declarator = state.getDeclarator();
461 
462   // objc_gc goes on the innermost pointer to something that's not a
463   // pointer.
464   unsigned innermost = -1U;
465   bool considerDeclSpec = true;
466   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
467     DeclaratorChunk &chunk = declarator.getTypeObject(i);
468     switch (chunk.Kind) {
469     case DeclaratorChunk::Pointer:
470     case DeclaratorChunk::BlockPointer:
471       innermost = i;
472       continue;
473 
474     case DeclaratorChunk::Reference:
475     case DeclaratorChunk::MemberPointer:
476     case DeclaratorChunk::Paren:
477     case DeclaratorChunk::Array:
478     case DeclaratorChunk::Pipe:
479       continue;
480 
481     case DeclaratorChunk::Function:
482       considerDeclSpec = false;
483       goto done;
484     }
485   }
486  done:
487 
488   // That might actually be the decl spec if we weren't blocked by
489   // anything in the declarator.
490   if (considerDeclSpec) {
491     if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
492       // Splice the attribute into the decl spec.  Prevents the
493       // attribute from being applied multiple times and gives
494       // the source-location-filler something to work with.
495       state.saveDeclSpecAttrs();
496       moveAttrFromListToList(attr, declarator.getAttrListRef(),
497                declarator.getMutableDeclSpec().getAttributes().getListRef());
498       return;
499     }
500   }
501 
502   // Otherwise, if we found an appropriate chunk, splice the attribute
503   // into it.
504   if (innermost != -1U) {
505     moveAttrFromListToList(attr, declarator.getAttrListRef(),
506                        declarator.getTypeObject(innermost).getAttrListRef());
507     return;
508   }
509 
510   // Otherwise, diagnose when we're done building the type.
511   spliceAttrOutOfList(attr, declarator.getAttrListRef());
512   state.addIgnoredTypeAttr(attr);
513 }
514 
515 /// A function type attribute was written somewhere in a declaration
516 /// *other* than on the declarator itself or in the decl spec.  Given
517 /// that it didn't apply in whatever position it was written in, try
518 /// to move it to a more appropriate position.
519 static void distributeFunctionTypeAttr(TypeProcessingState &state,
520                                        AttributeList &attr,
521                                        QualType type) {
522   Declarator &declarator = state.getDeclarator();
523 
524   // Try to push the attribute from the return type of a function to
525   // the function itself.
526   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
527     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
528     switch (chunk.Kind) {
529     case DeclaratorChunk::Function:
530       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
531                              chunk.getAttrListRef());
532       return;
533 
534     case DeclaratorChunk::Paren:
535     case DeclaratorChunk::Pointer:
536     case DeclaratorChunk::BlockPointer:
537     case DeclaratorChunk::Array:
538     case DeclaratorChunk::Reference:
539     case DeclaratorChunk::MemberPointer:
540     case DeclaratorChunk::Pipe:
541       continue;
542     }
543   }
544 
545   diagnoseBadTypeAttribute(state.getSema(), attr, type);
546 }
547 
548 /// Try to distribute a function type attribute to the innermost
549 /// function chunk or type.  Returns true if the attribute was
550 /// distributed, false if no location was found.
551 static bool
552 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
553                                       AttributeList &attr,
554                                       AttributeList *&attrList,
555                                       QualType &declSpecType) {
556   Declarator &declarator = state.getDeclarator();
557 
558   // Put it on the innermost function chunk, if there is one.
559   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
560     DeclaratorChunk &chunk = declarator.getTypeObject(i);
561     if (chunk.Kind != DeclaratorChunk::Function) continue;
562 
563     moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
564     return true;
565   }
566 
567   return handleFunctionTypeAttr(state, attr, declSpecType);
568 }
569 
570 /// A function type attribute was written in the decl spec.  Try to
571 /// apply it somewhere.
572 static void
573 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
574                                        AttributeList &attr,
575                                        QualType &declSpecType) {
576   state.saveDeclSpecAttrs();
577 
578   // C++11 attributes before the decl specifiers actually appertain to
579   // the declarators. Move them straight there. We don't support the
580   // 'put them wherever you like' semantics we allow for GNU attributes.
581   if (attr.isCXX11Attribute()) {
582     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
583                            state.getDeclarator().getAttrListRef());
584     return;
585   }
586 
587   // Try to distribute to the innermost.
588   if (distributeFunctionTypeAttrToInnermost(state, attr,
589                                             state.getCurrentAttrListRef(),
590                                             declSpecType))
591     return;
592 
593   // If that failed, diagnose the bad attribute when the declarator is
594   // fully built.
595   state.addIgnoredTypeAttr(attr);
596 }
597 
598 /// A function type attribute was written on the declarator.  Try to
599 /// apply it somewhere.
600 static void
601 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
602                                          AttributeList &attr,
603                                          QualType &declSpecType) {
604   Declarator &declarator = state.getDeclarator();
605 
606   // Try to distribute to the innermost.
607   if (distributeFunctionTypeAttrToInnermost(state, attr,
608                                             declarator.getAttrListRef(),
609                                             declSpecType))
610     return;
611 
612   // If that failed, diagnose the bad attribute when the declarator is
613   // fully built.
614   spliceAttrOutOfList(attr, declarator.getAttrListRef());
615   state.addIgnoredTypeAttr(attr);
616 }
617 
618 /// Given that there are attributes written on the declarator
619 /// itself, try to distribute any type attributes to the appropriate
620 /// declarator chunk.
621 ///
622 /// These are attributes like the following:
623 ///   int f ATTR;
624 ///   int (f ATTR)();
625 /// but not necessarily this:
626 ///   int f() ATTR;
627 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
628                                               QualType &declSpecType) {
629   // Collect all the type attributes from the declarator itself.
630   assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
631   AttributeList *attr = state.getDeclarator().getAttributes();
632   AttributeList *next;
633   do {
634     next = attr->getNext();
635 
636     // Do not distribute C++11 attributes. They have strict rules for what
637     // they appertain to.
638     if (attr->isCXX11Attribute())
639       continue;
640 
641     switch (attr->getKind()) {
642     OBJC_POINTER_TYPE_ATTRS_CASELIST:
643       distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
644       break;
645 
646     FUNCTION_TYPE_ATTRS_CASELIST:
647       distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
648       break;
649 
650     MS_TYPE_ATTRS_CASELIST:
651       // Microsoft type attributes cannot go after the declarator-id.
652       continue;
653 
654     NULLABILITY_TYPE_ATTRS_CASELIST:
655       // Nullability specifiers cannot go after the declarator-id.
656 
657     // Objective-C __kindof does not get distributed.
658     case AttributeList::AT_ObjCKindOf:
659       continue;
660 
661     default:
662       break;
663     }
664   } while ((attr = next));
665 }
666 
667 /// Add a synthetic '()' to a block-literal declarator if it is
668 /// required, given the return type.
669 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
670                                           QualType declSpecType) {
671   Declarator &declarator = state.getDeclarator();
672 
673   // First, check whether the declarator would produce a function,
674   // i.e. whether the innermost semantic chunk is a function.
675   if (declarator.isFunctionDeclarator()) {
676     // If so, make that declarator a prototyped declarator.
677     declarator.getFunctionTypeInfo().hasPrototype = true;
678     return;
679   }
680 
681   // If there are any type objects, the type as written won't name a
682   // function, regardless of the decl spec type.  This is because a
683   // block signature declarator is always an abstract-declarator, and
684   // abstract-declarators can't just be parentheses chunks.  Therefore
685   // we need to build a function chunk unless there are no type
686   // objects and the decl spec type is a function.
687   if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
688     return;
689 
690   // Note that there *are* cases with invalid declarators where
691   // declarators consist solely of parentheses.  In general, these
692   // occur only in failed efforts to make function declarators, so
693   // faking up the function chunk is still the right thing to do.
694 
695   // Otherwise, we need to fake up a function declarator.
696   SourceLocation loc = declarator.getLocStart();
697 
698   // ...and *prepend* it to the declarator.
699   SourceLocation NoLoc;
700   declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
701       /*HasProto=*/true,
702       /*IsAmbiguous=*/false,
703       /*LParenLoc=*/NoLoc,
704       /*ArgInfo=*/nullptr,
705       /*NumArgs=*/0,
706       /*EllipsisLoc=*/NoLoc,
707       /*RParenLoc=*/NoLoc,
708       /*TypeQuals=*/0,
709       /*RefQualifierIsLvalueRef=*/true,
710       /*RefQualifierLoc=*/NoLoc,
711       /*ConstQualifierLoc=*/NoLoc,
712       /*VolatileQualifierLoc=*/NoLoc,
713       /*RestrictQualifierLoc=*/NoLoc,
714       /*MutableLoc=*/NoLoc, EST_None,
715       /*ESpecRange=*/SourceRange(),
716       /*Exceptions=*/nullptr,
717       /*ExceptionRanges=*/nullptr,
718       /*NumExceptions=*/0,
719       /*NoexceptExpr=*/nullptr,
720       /*ExceptionSpecTokens=*/nullptr,
721       /*DeclsInPrototype=*/None,
722       loc, loc, declarator));
723 
724   // For consistency, make sure the state still has us as processing
725   // the decl spec.
726   assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
727   state.setCurrentChunkIndex(declarator.getNumTypeObjects());
728 }
729 
730 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
731                                             unsigned &TypeQuals,
732                                             QualType TypeSoFar,
733                                             unsigned RemoveTQs,
734                                             unsigned DiagID) {
735   // If this occurs outside a template instantiation, warn the user about
736   // it; they probably didn't mean to specify a redundant qualifier.
737   typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
738   for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
739                        QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
740                        QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
741                        QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
742     if (!(RemoveTQs & Qual.first))
743       continue;
744 
745     if (!S.inTemplateInstantiation()) {
746       if (TypeQuals & Qual.first)
747         S.Diag(Qual.second, DiagID)
748           << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
749           << FixItHint::CreateRemoval(Qual.second);
750     }
751 
752     TypeQuals &= ~Qual.first;
753   }
754 }
755 
756 /// Return true if this is omitted block return type. Also check type
757 /// attributes and type qualifiers when returning true.
758 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
759                                         QualType Result) {
760   if (!isOmittedBlockReturnType(declarator))
761     return false;
762 
763   // Warn if we see type attributes for omitted return type on a block literal.
764   AttributeList *&attrs =
765       declarator.getMutableDeclSpec().getAttributes().getListRef();
766   AttributeList *prev = nullptr;
767   for (AttributeList *cur = attrs; cur; cur = cur->getNext()) {
768     AttributeList &attr = *cur;
769     // Skip attributes that were marked to be invalid or non-type
770     // attributes.
771     if (attr.isInvalid() || !attr.isTypeAttr()) {
772       prev = cur;
773       continue;
774     }
775     S.Diag(attr.getLoc(),
776            diag::warn_block_literal_attributes_on_omitted_return_type)
777         << attr.getName();
778     // Remove cur from the list.
779     if (prev) {
780       prev->setNext(cur->getNext());
781       prev = cur;
782     } else {
783       attrs = cur->getNext();
784     }
785   }
786 
787   // Warn if we see type qualifiers for omitted return type on a block literal.
788   const DeclSpec &DS = declarator.getDeclSpec();
789   unsigned TypeQuals = DS.getTypeQualifiers();
790   diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
791       diag::warn_block_literal_qualifiers_on_omitted_return_type);
792   declarator.getMutableDeclSpec().ClearTypeQualifiers();
793 
794   return true;
795 }
796 
797 /// Apply Objective-C type arguments to the given type.
798 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
799                                   ArrayRef<TypeSourceInfo *> typeArgs,
800                                   SourceRange typeArgsRange,
801                                   bool failOnError = false) {
802   // We can only apply type arguments to an Objective-C class type.
803   const auto *objcObjectType = type->getAs<ObjCObjectType>();
804   if (!objcObjectType || !objcObjectType->getInterface()) {
805     S.Diag(loc, diag::err_objc_type_args_non_class)
806       << type
807       << typeArgsRange;
808 
809     if (failOnError)
810       return QualType();
811     return type;
812   }
813 
814   // The class type must be parameterized.
815   ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
816   ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
817   if (!typeParams) {
818     S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
819       << objcClass->getDeclName()
820       << FixItHint::CreateRemoval(typeArgsRange);
821 
822     if (failOnError)
823       return QualType();
824 
825     return type;
826   }
827 
828   // The type must not already be specialized.
829   if (objcObjectType->isSpecialized()) {
830     S.Diag(loc, diag::err_objc_type_args_specialized_class)
831       << type
832       << FixItHint::CreateRemoval(typeArgsRange);
833 
834     if (failOnError)
835       return QualType();
836 
837     return type;
838   }
839 
840   // Check the type arguments.
841   SmallVector<QualType, 4> finalTypeArgs;
842   unsigned numTypeParams = typeParams->size();
843   bool anyPackExpansions = false;
844   for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
845     TypeSourceInfo *typeArgInfo = typeArgs[i];
846     QualType typeArg = typeArgInfo->getType();
847 
848     // Type arguments cannot have explicit qualifiers or nullability.
849     // We ignore indirect sources of these, e.g. behind typedefs or
850     // template arguments.
851     if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
852       bool diagnosed = false;
853       SourceRange rangeToRemove;
854       if (auto attr = qual.getAs<AttributedTypeLoc>()) {
855         rangeToRemove = attr.getLocalSourceRange();
856         if (attr.getTypePtr()->getImmediateNullability()) {
857           typeArg = attr.getTypePtr()->getModifiedType();
858           S.Diag(attr.getLocStart(),
859                  diag::err_objc_type_arg_explicit_nullability)
860             << typeArg << FixItHint::CreateRemoval(rangeToRemove);
861           diagnosed = true;
862         }
863       }
864 
865       if (!diagnosed) {
866         S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
867           << typeArg << typeArg.getQualifiers().getAsString()
868           << FixItHint::CreateRemoval(rangeToRemove);
869       }
870     }
871 
872     // Remove qualifiers even if they're non-local.
873     typeArg = typeArg.getUnqualifiedType();
874 
875     finalTypeArgs.push_back(typeArg);
876 
877     if (typeArg->getAs<PackExpansionType>())
878       anyPackExpansions = true;
879 
880     // Find the corresponding type parameter, if there is one.
881     ObjCTypeParamDecl *typeParam = nullptr;
882     if (!anyPackExpansions) {
883       if (i < numTypeParams) {
884         typeParam = typeParams->begin()[i];
885       } else {
886         // Too many arguments.
887         S.Diag(loc, diag::err_objc_type_args_wrong_arity)
888           << false
889           << objcClass->getDeclName()
890           << (unsigned)typeArgs.size()
891           << numTypeParams;
892         S.Diag(objcClass->getLocation(), diag::note_previous_decl)
893           << objcClass;
894 
895         if (failOnError)
896           return QualType();
897 
898         return type;
899       }
900     }
901 
902     // Objective-C object pointer types must be substitutable for the bounds.
903     if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
904       // If we don't have a type parameter to match against, assume
905       // everything is fine. There was a prior pack expansion that
906       // means we won't be able to match anything.
907       if (!typeParam) {
908         assert(anyPackExpansions && "Too many arguments?");
909         continue;
910       }
911 
912       // Retrieve the bound.
913       QualType bound = typeParam->getUnderlyingType();
914       const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
915 
916       // Determine whether the type argument is substitutable for the bound.
917       if (typeArgObjC->isObjCIdType()) {
918         // When the type argument is 'id', the only acceptable type
919         // parameter bound is 'id'.
920         if (boundObjC->isObjCIdType())
921           continue;
922       } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
923         // Otherwise, we follow the assignability rules.
924         continue;
925       }
926 
927       // Diagnose the mismatch.
928       S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
929              diag::err_objc_type_arg_does_not_match_bound)
930         << typeArg << bound << typeParam->getDeclName();
931       S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
932         << typeParam->getDeclName();
933 
934       if (failOnError)
935         return QualType();
936 
937       return type;
938     }
939 
940     // Block pointer types are permitted for unqualified 'id' bounds.
941     if (typeArg->isBlockPointerType()) {
942       // If we don't have a type parameter to match against, assume
943       // everything is fine. There was a prior pack expansion that
944       // means we won't be able to match anything.
945       if (!typeParam) {
946         assert(anyPackExpansions && "Too many arguments?");
947         continue;
948       }
949 
950       // Retrieve the bound.
951       QualType bound = typeParam->getUnderlyingType();
952       if (bound->isBlockCompatibleObjCPointerType(S.Context))
953         continue;
954 
955       // Diagnose the mismatch.
956       S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
957              diag::err_objc_type_arg_does_not_match_bound)
958         << typeArg << bound << typeParam->getDeclName();
959       S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
960         << typeParam->getDeclName();
961 
962       if (failOnError)
963         return QualType();
964 
965       return type;
966     }
967 
968     // Dependent types will be checked at instantiation time.
969     if (typeArg->isDependentType()) {
970       continue;
971     }
972 
973     // Diagnose non-id-compatible type arguments.
974     S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
975            diag::err_objc_type_arg_not_id_compatible)
976       << typeArg
977       << typeArgInfo->getTypeLoc().getSourceRange();
978 
979     if (failOnError)
980       return QualType();
981 
982     return type;
983   }
984 
985   // Make sure we didn't have the wrong number of arguments.
986   if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
987     S.Diag(loc, diag::err_objc_type_args_wrong_arity)
988       << (typeArgs.size() < typeParams->size())
989       << objcClass->getDeclName()
990       << (unsigned)finalTypeArgs.size()
991       << (unsigned)numTypeParams;
992     S.Diag(objcClass->getLocation(), diag::note_previous_decl)
993       << objcClass;
994 
995     if (failOnError)
996       return QualType();
997 
998     return type;
999   }
1000 
1001   // Success. Form the specialized type.
1002   return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1003 }
1004 
1005 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1006                                       SourceLocation ProtocolLAngleLoc,
1007                                       ArrayRef<ObjCProtocolDecl *> Protocols,
1008                                       ArrayRef<SourceLocation> ProtocolLocs,
1009                                       SourceLocation ProtocolRAngleLoc,
1010                                       bool FailOnError) {
1011   QualType Result = QualType(Decl->getTypeForDecl(), 0);
1012   if (!Protocols.empty()) {
1013     bool HasError;
1014     Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1015                                                  HasError);
1016     if (HasError) {
1017       Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1018         << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1019       if (FailOnError) Result = QualType();
1020     }
1021     if (FailOnError && Result.isNull())
1022       return QualType();
1023   }
1024 
1025   return Result;
1026 }
1027 
1028 QualType Sema::BuildObjCObjectType(QualType BaseType,
1029                                    SourceLocation Loc,
1030                                    SourceLocation TypeArgsLAngleLoc,
1031                                    ArrayRef<TypeSourceInfo *> TypeArgs,
1032                                    SourceLocation TypeArgsRAngleLoc,
1033                                    SourceLocation ProtocolLAngleLoc,
1034                                    ArrayRef<ObjCProtocolDecl *> Protocols,
1035                                    ArrayRef<SourceLocation> ProtocolLocs,
1036                                    SourceLocation ProtocolRAngleLoc,
1037                                    bool FailOnError) {
1038   QualType Result = BaseType;
1039   if (!TypeArgs.empty()) {
1040     Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1041                                SourceRange(TypeArgsLAngleLoc,
1042                                            TypeArgsRAngleLoc),
1043                                FailOnError);
1044     if (FailOnError && Result.isNull())
1045       return QualType();
1046   }
1047 
1048   if (!Protocols.empty()) {
1049     bool HasError;
1050     Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1051                                                  HasError);
1052     if (HasError) {
1053       Diag(Loc, diag::err_invalid_protocol_qualifiers)
1054         << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1055       if (FailOnError) Result = QualType();
1056     }
1057     if (FailOnError && Result.isNull())
1058       return QualType();
1059   }
1060 
1061   return Result;
1062 }
1063 
1064 TypeResult Sema::actOnObjCProtocolQualifierType(
1065              SourceLocation lAngleLoc,
1066              ArrayRef<Decl *> protocols,
1067              ArrayRef<SourceLocation> protocolLocs,
1068              SourceLocation rAngleLoc) {
1069   // Form id<protocol-list>.
1070   QualType Result = Context.getObjCObjectType(
1071                       Context.ObjCBuiltinIdTy, { },
1072                       llvm::makeArrayRef(
1073                         (ObjCProtocolDecl * const *)protocols.data(),
1074                         protocols.size()),
1075                       false);
1076   Result = Context.getObjCObjectPointerType(Result);
1077 
1078   TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1079   TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1080 
1081   auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1082   ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1083 
1084   auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1085                         .castAs<ObjCObjectTypeLoc>();
1086   ObjCObjectTL.setHasBaseTypeAsWritten(false);
1087   ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1088 
1089   // No type arguments.
1090   ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1091   ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1092 
1093   // Fill in protocol qualifiers.
1094   ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1095   ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1096   for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1097     ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1098 
1099   // We're done. Return the completed type to the parser.
1100   return CreateParsedType(Result, ResultTInfo);
1101 }
1102 
1103 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1104              Scope *S,
1105              SourceLocation Loc,
1106              ParsedType BaseType,
1107              SourceLocation TypeArgsLAngleLoc,
1108              ArrayRef<ParsedType> TypeArgs,
1109              SourceLocation TypeArgsRAngleLoc,
1110              SourceLocation ProtocolLAngleLoc,
1111              ArrayRef<Decl *> Protocols,
1112              ArrayRef<SourceLocation> ProtocolLocs,
1113              SourceLocation ProtocolRAngleLoc) {
1114   TypeSourceInfo *BaseTypeInfo = nullptr;
1115   QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1116   if (T.isNull())
1117     return true;
1118 
1119   // Handle missing type-source info.
1120   if (!BaseTypeInfo)
1121     BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1122 
1123   // Extract type arguments.
1124   SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1125   for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1126     TypeSourceInfo *TypeArgInfo = nullptr;
1127     QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1128     if (TypeArg.isNull()) {
1129       ActualTypeArgInfos.clear();
1130       break;
1131     }
1132 
1133     assert(TypeArgInfo && "No type source info?");
1134     ActualTypeArgInfos.push_back(TypeArgInfo);
1135   }
1136 
1137   // Build the object type.
1138   QualType Result = BuildObjCObjectType(
1139       T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1140       TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1141       ProtocolLAngleLoc,
1142       llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1143                          Protocols.size()),
1144       ProtocolLocs, ProtocolRAngleLoc,
1145       /*FailOnError=*/false);
1146 
1147   if (Result == T)
1148     return BaseType;
1149 
1150   // Create source information for this type.
1151   TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1152   TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1153 
1154   // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1155   // object pointer type. Fill in source information for it.
1156   if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1157     // The '*' is implicit.
1158     ObjCObjectPointerTL.setStarLoc(SourceLocation());
1159     ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1160   }
1161 
1162   if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1163     // Protocol qualifier information.
1164     if (OTPTL.getNumProtocols() > 0) {
1165       assert(OTPTL.getNumProtocols() == Protocols.size());
1166       OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1167       OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1168       for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1169         OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1170     }
1171 
1172     // We're done. Return the completed type to the parser.
1173     return CreateParsedType(Result, ResultTInfo);
1174   }
1175 
1176   auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1177 
1178   // Type argument information.
1179   if (ObjCObjectTL.getNumTypeArgs() > 0) {
1180     assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1181     ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1182     ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1183     for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1184       ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1185   } else {
1186     ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1187     ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1188   }
1189 
1190   // Protocol qualifier information.
1191   if (ObjCObjectTL.getNumProtocols() > 0) {
1192     assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1193     ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1194     ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1195     for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1196       ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1197   } else {
1198     ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1199     ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1200   }
1201 
1202   // Base type.
1203   ObjCObjectTL.setHasBaseTypeAsWritten(true);
1204   if (ObjCObjectTL.getType() == T)
1205     ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1206   else
1207     ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1208 
1209   // We're done. Return the completed type to the parser.
1210   return CreateParsedType(Result, ResultTInfo);
1211 }
1212 
1213 static OpenCLAccessAttr::Spelling getImageAccess(const AttributeList *Attrs) {
1214   if (Attrs) {
1215     const AttributeList *Next = Attrs;
1216     do {
1217       const AttributeList &Attr = *Next;
1218       Next = Attr.getNext();
1219       if (Attr.getKind() == AttributeList::AT_OpenCLAccess) {
1220         return static_cast<OpenCLAccessAttr::Spelling>(
1221             Attr.getSemanticSpelling());
1222       }
1223     } while (Next);
1224   }
1225   return OpenCLAccessAttr::Keyword_read_only;
1226 }
1227 
1228 /// Convert the specified declspec to the appropriate type
1229 /// object.
1230 /// \param state Specifies the declarator containing the declaration specifier
1231 /// to be converted, along with other associated processing state.
1232 /// \returns The type described by the declaration specifiers.  This function
1233 /// never returns null.
1234 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1235   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1236   // checking.
1237 
1238   Sema &S = state.getSema();
1239   Declarator &declarator = state.getDeclarator();
1240   const DeclSpec &DS = declarator.getDeclSpec();
1241   SourceLocation DeclLoc = declarator.getIdentifierLoc();
1242   if (DeclLoc.isInvalid())
1243     DeclLoc = DS.getLocStart();
1244 
1245   ASTContext &Context = S.Context;
1246 
1247   QualType Result;
1248   switch (DS.getTypeSpecType()) {
1249   case DeclSpec::TST_void:
1250     Result = Context.VoidTy;
1251     break;
1252   case DeclSpec::TST_char:
1253     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1254       Result = Context.CharTy;
1255     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1256       Result = Context.SignedCharTy;
1257     else {
1258       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1259              "Unknown TSS value");
1260       Result = Context.UnsignedCharTy;
1261     }
1262     break;
1263   case DeclSpec::TST_wchar:
1264     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1265       Result = Context.WCharTy;
1266     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1267       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1268         << DS.getSpecifierName(DS.getTypeSpecType(),
1269                                Context.getPrintingPolicy());
1270       Result = Context.getSignedWCharType();
1271     } else {
1272       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1273         "Unknown TSS value");
1274       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1275         << DS.getSpecifierName(DS.getTypeSpecType(),
1276                                Context.getPrintingPolicy());
1277       Result = Context.getUnsignedWCharType();
1278     }
1279     break;
1280   case DeclSpec::TST_char8:
1281       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1282         "Unknown TSS value");
1283       Result = Context.Char8Ty;
1284     break;
1285   case DeclSpec::TST_char16:
1286       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1287         "Unknown TSS value");
1288       Result = Context.Char16Ty;
1289     break;
1290   case DeclSpec::TST_char32:
1291       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1292         "Unknown TSS value");
1293       Result = Context.Char32Ty;
1294     break;
1295   case DeclSpec::TST_unspecified:
1296     // If this is a missing declspec in a block literal return context, then it
1297     // is inferred from the return statements inside the block.
1298     // The declspec is always missing in a lambda expr context; it is either
1299     // specified with a trailing return type or inferred.
1300     if (S.getLangOpts().CPlusPlus14 &&
1301         declarator.getContext() == DeclaratorContext::LambdaExprContext) {
1302       // In C++1y, a lambda's implicit return type is 'auto'.
1303       Result = Context.getAutoDeductType();
1304       break;
1305     } else if (declarator.getContext() ==
1306                    DeclaratorContext::LambdaExprContext ||
1307                checkOmittedBlockReturnType(S, declarator,
1308                                            Context.DependentTy)) {
1309       Result = Context.DependentTy;
1310       break;
1311     }
1312 
1313     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
1314     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1315     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
1316     // Note that the one exception to this is function definitions, which are
1317     // allowed to be completely missing a declspec.  This is handled in the
1318     // parser already though by it pretending to have seen an 'int' in this
1319     // case.
1320     if (S.getLangOpts().ImplicitInt) {
1321       // In C89 mode, we only warn if there is a completely missing declspec
1322       // when one is not allowed.
1323       if (DS.isEmpty()) {
1324         S.Diag(DeclLoc, diag::ext_missing_declspec)
1325           << DS.getSourceRange()
1326         << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1327       }
1328     } else if (!DS.hasTypeSpecifier()) {
1329       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
1330       // "At least one type specifier shall be given in the declaration
1331       // specifiers in each declaration, and in the specifier-qualifier list in
1332       // each struct declaration and type name."
1333       if (S.getLangOpts().CPlusPlus) {
1334         S.Diag(DeclLoc, diag::err_missing_type_specifier)
1335           << DS.getSourceRange();
1336 
1337         // When this occurs in C++ code, often something is very broken with the
1338         // value being declared, poison it as invalid so we don't get chains of
1339         // errors.
1340         declarator.setInvalidType(true);
1341       } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1342         S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1343           << DS.getSourceRange();
1344         declarator.setInvalidType(true);
1345       } else {
1346         S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1347           << DS.getSourceRange();
1348       }
1349     }
1350 
1351     LLVM_FALLTHROUGH;
1352   case DeclSpec::TST_int: {
1353     if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1354       switch (DS.getTypeSpecWidth()) {
1355       case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1356       case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
1357       case DeclSpec::TSW_long:        Result = Context.LongTy; break;
1358       case DeclSpec::TSW_longlong:
1359         Result = Context.LongLongTy;
1360 
1361         // 'long long' is a C99 or C++11 feature.
1362         if (!S.getLangOpts().C99) {
1363           if (S.getLangOpts().CPlusPlus)
1364             S.Diag(DS.getTypeSpecWidthLoc(),
1365                    S.getLangOpts().CPlusPlus11 ?
1366                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1367           else
1368             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1369         }
1370         break;
1371       }
1372     } else {
1373       switch (DS.getTypeSpecWidth()) {
1374       case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1375       case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
1376       case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
1377       case DeclSpec::TSW_longlong:
1378         Result = Context.UnsignedLongLongTy;
1379 
1380         // 'long long' is a C99 or C++11 feature.
1381         if (!S.getLangOpts().C99) {
1382           if (S.getLangOpts().CPlusPlus)
1383             S.Diag(DS.getTypeSpecWidthLoc(),
1384                    S.getLangOpts().CPlusPlus11 ?
1385                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1386           else
1387             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1388         }
1389         break;
1390       }
1391     }
1392     break;
1393   }
1394   case DeclSpec::TST_accum: {
1395     switch (DS.getTypeSpecWidth()) {
1396       case DeclSpec::TSW_short:
1397         Result = Context.ShortAccumTy;
1398         break;
1399       case DeclSpec::TSW_unspecified:
1400         Result = Context.AccumTy;
1401         break;
1402       case DeclSpec::TSW_long:
1403         Result = Context.LongAccumTy;
1404         break;
1405       case DeclSpec::TSW_longlong:
1406         llvm_unreachable("Unable to specify long long as _Accum width");
1407     }
1408 
1409     if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1410       Result = Context.getCorrespondingUnsignedType(Result);
1411 
1412     if (DS.isTypeSpecSat())
1413       Result = Context.getCorrespondingSaturatedType(Result);
1414 
1415     break;
1416   }
1417   case DeclSpec::TST_fract: {
1418     switch (DS.getTypeSpecWidth()) {
1419       case DeclSpec::TSW_short:
1420         Result = Context.ShortFractTy;
1421         break;
1422       case DeclSpec::TSW_unspecified:
1423         Result = Context.FractTy;
1424         break;
1425       case DeclSpec::TSW_long:
1426         Result = Context.LongFractTy;
1427         break;
1428       case DeclSpec::TSW_longlong:
1429         llvm_unreachable("Unable to specify long long as _Fract width");
1430     }
1431 
1432     if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1433       Result = Context.getCorrespondingUnsignedType(Result);
1434 
1435     if (DS.isTypeSpecSat())
1436       Result = Context.getCorrespondingSaturatedType(Result);
1437 
1438     break;
1439   }
1440   case DeclSpec::TST_int128:
1441     if (!S.Context.getTargetInfo().hasInt128Type())
1442       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1443         << "__int128";
1444     if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1445       Result = Context.UnsignedInt128Ty;
1446     else
1447       Result = Context.Int128Ty;
1448     break;
1449   case DeclSpec::TST_float16: Result = Context.Float16Ty; break;
1450   case DeclSpec::TST_half:    Result = Context.HalfTy; break;
1451   case DeclSpec::TST_float:   Result = Context.FloatTy; break;
1452   case DeclSpec::TST_double:
1453     if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1454       Result = Context.LongDoubleTy;
1455     else
1456       Result = Context.DoubleTy;
1457     break;
1458   case DeclSpec::TST_float128:
1459     if (!S.Context.getTargetInfo().hasFloat128Type())
1460       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1461         << "__float128";
1462     Result = Context.Float128Ty;
1463     break;
1464   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1465     break;
1466   case DeclSpec::TST_decimal32:    // _Decimal32
1467   case DeclSpec::TST_decimal64:    // _Decimal64
1468   case DeclSpec::TST_decimal128:   // _Decimal128
1469     S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1470     Result = Context.IntTy;
1471     declarator.setInvalidType(true);
1472     break;
1473   case DeclSpec::TST_class:
1474   case DeclSpec::TST_enum:
1475   case DeclSpec::TST_union:
1476   case DeclSpec::TST_struct:
1477   case DeclSpec::TST_interface: {
1478     TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1479     if (!D) {
1480       // This can happen in C++ with ambiguous lookups.
1481       Result = Context.IntTy;
1482       declarator.setInvalidType(true);
1483       break;
1484     }
1485 
1486     // If the type is deprecated or unavailable, diagnose it.
1487     S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1488 
1489     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1490            DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1491 
1492     // TypeQuals handled by caller.
1493     Result = Context.getTypeDeclType(D);
1494 
1495     // In both C and C++, make an ElaboratedType.
1496     ElaboratedTypeKeyword Keyword
1497       = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1498     Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1499                                  DS.isTypeSpecOwned() ? D : nullptr);
1500     break;
1501   }
1502   case DeclSpec::TST_typename: {
1503     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1504            DS.getTypeSpecSign() == 0 &&
1505            "Can't handle qualifiers on typedef names yet!");
1506     Result = S.GetTypeFromParser(DS.getRepAsType());
1507     if (Result.isNull()) {
1508       declarator.setInvalidType(true);
1509     }
1510 
1511     // TypeQuals handled by caller.
1512     break;
1513   }
1514   case DeclSpec::TST_typeofType:
1515     // FIXME: Preserve type source info.
1516     Result = S.GetTypeFromParser(DS.getRepAsType());
1517     assert(!Result.isNull() && "Didn't get a type for typeof?");
1518     if (!Result->isDependentType())
1519       if (const TagType *TT = Result->getAs<TagType>())
1520         S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1521     // TypeQuals handled by caller.
1522     Result = Context.getTypeOfType(Result);
1523     break;
1524   case DeclSpec::TST_typeofExpr: {
1525     Expr *E = DS.getRepAsExpr();
1526     assert(E && "Didn't get an expression for typeof?");
1527     // TypeQuals handled by caller.
1528     Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1529     if (Result.isNull()) {
1530       Result = Context.IntTy;
1531       declarator.setInvalidType(true);
1532     }
1533     break;
1534   }
1535   case DeclSpec::TST_decltype: {
1536     Expr *E = DS.getRepAsExpr();
1537     assert(E && "Didn't get an expression for decltype?");
1538     // TypeQuals handled by caller.
1539     Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1540     if (Result.isNull()) {
1541       Result = Context.IntTy;
1542       declarator.setInvalidType(true);
1543     }
1544     break;
1545   }
1546   case DeclSpec::TST_underlyingType:
1547     Result = S.GetTypeFromParser(DS.getRepAsType());
1548     assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1549     Result = S.BuildUnaryTransformType(Result,
1550                                        UnaryTransformType::EnumUnderlyingType,
1551                                        DS.getTypeSpecTypeLoc());
1552     if (Result.isNull()) {
1553       Result = Context.IntTy;
1554       declarator.setInvalidType(true);
1555     }
1556     break;
1557 
1558   case DeclSpec::TST_auto:
1559     Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1560     break;
1561 
1562   case DeclSpec::TST_auto_type:
1563     Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1564     break;
1565 
1566   case DeclSpec::TST_decltype_auto:
1567     Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1568                                  /*IsDependent*/ false);
1569     break;
1570 
1571   case DeclSpec::TST_unknown_anytype:
1572     Result = Context.UnknownAnyTy;
1573     break;
1574 
1575   case DeclSpec::TST_atomic:
1576     Result = S.GetTypeFromParser(DS.getRepAsType());
1577     assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1578     Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1579     if (Result.isNull()) {
1580       Result = Context.IntTy;
1581       declarator.setInvalidType(true);
1582     }
1583     break;
1584 
1585 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1586   case DeclSpec::TST_##ImgType##_t: \
1587     switch (getImageAccess(DS.getAttributes().getList())) { \
1588     case OpenCLAccessAttr::Keyword_write_only: \
1589       Result = Context.Id##WOTy; break; \
1590     case OpenCLAccessAttr::Keyword_read_write: \
1591       Result = Context.Id##RWTy; break; \
1592     case OpenCLAccessAttr::Keyword_read_only: \
1593       Result = Context.Id##ROTy; break; \
1594     } \
1595     break;
1596 #include "clang/Basic/OpenCLImageTypes.def"
1597 
1598   case DeclSpec::TST_error:
1599     Result = Context.IntTy;
1600     declarator.setInvalidType(true);
1601     break;
1602   }
1603 
1604   if (S.getLangOpts().OpenCL &&
1605       S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
1606     declarator.setInvalidType(true);
1607 
1608   bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1609                           DS.getTypeSpecType() == DeclSpec::TST_fract;
1610 
1611   // Only fixed point types can be saturated
1612   if (DS.isTypeSpecSat() && !IsFixedPointType)
1613     S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1614         << DS.getSpecifierName(DS.getTypeSpecType(),
1615                                Context.getPrintingPolicy());
1616 
1617   // Handle complex types.
1618   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1619     if (S.getLangOpts().Freestanding)
1620       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1621     Result = Context.getComplexType(Result);
1622   } else if (DS.isTypeAltiVecVector()) {
1623     unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1624     assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1625     VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1626     if (DS.isTypeAltiVecPixel())
1627       VecKind = VectorType::AltiVecPixel;
1628     else if (DS.isTypeAltiVecBool())
1629       VecKind = VectorType::AltiVecBool;
1630     Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1631   }
1632 
1633   // FIXME: Imaginary.
1634   if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1635     S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1636 
1637   // Before we process any type attributes, synthesize a block literal
1638   // function declarator if necessary.
1639   if (declarator.getContext() == DeclaratorContext::BlockLiteralContext)
1640     maybeSynthesizeBlockSignature(state, Result);
1641 
1642   // Apply any type attributes from the decl spec.  This may cause the
1643   // list of type attributes to be temporarily saved while the type
1644   // attributes are pushed around.
1645   // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1646   if (!DS.isTypeSpecPipe())
1647       processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1648 
1649   // Apply const/volatile/restrict qualifiers to T.
1650   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1651     // Warn about CV qualifiers on function types.
1652     // C99 6.7.3p8:
1653     //   If the specification of a function type includes any type qualifiers,
1654     //   the behavior is undefined.
1655     // C++11 [dcl.fct]p7:
1656     //   The effect of a cv-qualifier-seq in a function declarator is not the
1657     //   same as adding cv-qualification on top of the function type. In the
1658     //   latter case, the cv-qualifiers are ignored.
1659     if (TypeQuals && Result->isFunctionType()) {
1660       diagnoseAndRemoveTypeQualifiers(
1661           S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1662           S.getLangOpts().CPlusPlus
1663               ? diag::warn_typecheck_function_qualifiers_ignored
1664               : diag::warn_typecheck_function_qualifiers_unspecified);
1665       // No diagnostic for 'restrict' or '_Atomic' applied to a
1666       // function type; we'll diagnose those later, in BuildQualifiedType.
1667     }
1668 
1669     // C++11 [dcl.ref]p1:
1670     //   Cv-qualified references are ill-formed except when the
1671     //   cv-qualifiers are introduced through the use of a typedef-name
1672     //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1673     //
1674     // There don't appear to be any other contexts in which a cv-qualified
1675     // reference type could be formed, so the 'ill-formed' clause here appears
1676     // to never happen.
1677     if (TypeQuals && Result->isReferenceType()) {
1678       diagnoseAndRemoveTypeQualifiers(
1679           S, DS, TypeQuals, Result,
1680           DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1681           diag::warn_typecheck_reference_qualifiers);
1682     }
1683 
1684     // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1685     // than once in the same specifier-list or qualifier-list, either directly
1686     // or via one or more typedefs."
1687     if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1688         && TypeQuals & Result.getCVRQualifiers()) {
1689       if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1690         S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1691           << "const";
1692       }
1693 
1694       if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1695         S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1696           << "volatile";
1697       }
1698 
1699       // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1700       // produce a warning in this case.
1701     }
1702 
1703     QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1704 
1705     // If adding qualifiers fails, just use the unqualified type.
1706     if (Qualified.isNull())
1707       declarator.setInvalidType(true);
1708     else
1709       Result = Qualified;
1710   }
1711 
1712   assert(!Result.isNull() && "This function should not return a null type");
1713   return Result;
1714 }
1715 
1716 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1717   if (Entity)
1718     return Entity.getAsString();
1719 
1720   return "type name";
1721 }
1722 
1723 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1724                                   Qualifiers Qs, const DeclSpec *DS) {
1725   if (T.isNull())
1726     return QualType();
1727 
1728   // Ignore any attempt to form a cv-qualified reference.
1729   if (T->isReferenceType()) {
1730     Qs.removeConst();
1731     Qs.removeVolatile();
1732   }
1733 
1734   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1735   // object or incomplete types shall not be restrict-qualified."
1736   if (Qs.hasRestrict()) {
1737     unsigned DiagID = 0;
1738     QualType ProblemTy;
1739 
1740     if (T->isAnyPointerType() || T->isReferenceType() ||
1741         T->isMemberPointerType()) {
1742       QualType EltTy;
1743       if (T->isObjCObjectPointerType())
1744         EltTy = T;
1745       else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1746         EltTy = PTy->getPointeeType();
1747       else
1748         EltTy = T->getPointeeType();
1749 
1750       // If we have a pointer or reference, the pointee must have an object
1751       // incomplete type.
1752       if (!EltTy->isIncompleteOrObjectType()) {
1753         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1754         ProblemTy = EltTy;
1755       }
1756     } else if (!T->isDependentType()) {
1757       DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1758       ProblemTy = T;
1759     }
1760 
1761     if (DiagID) {
1762       Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1763       Qs.removeRestrict();
1764     }
1765   }
1766 
1767   return Context.getQualifiedType(T, Qs);
1768 }
1769 
1770 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1771                                   unsigned CVRAU, const DeclSpec *DS) {
1772   if (T.isNull())
1773     return QualType();
1774 
1775   // Ignore any attempt to form a cv-qualified reference.
1776   if (T->isReferenceType())
1777     CVRAU &=
1778         ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1779 
1780   // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1781   // TQ_unaligned;
1782   unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1783 
1784   // C11 6.7.3/5:
1785   //   If the same qualifier appears more than once in the same
1786   //   specifier-qualifier-list, either directly or via one or more typedefs,
1787   //   the behavior is the same as if it appeared only once.
1788   //
1789   // It's not specified what happens when the _Atomic qualifier is applied to
1790   // a type specified with the _Atomic specifier, but we assume that this
1791   // should be treated as if the _Atomic qualifier appeared multiple times.
1792   if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1793     // C11 6.7.3/5:
1794     //   If other qualifiers appear along with the _Atomic qualifier in a
1795     //   specifier-qualifier-list, the resulting type is the so-qualified
1796     //   atomic type.
1797     //
1798     // Don't need to worry about array types here, since _Atomic can't be
1799     // applied to such types.
1800     SplitQualType Split = T.getSplitUnqualifiedType();
1801     T = BuildAtomicType(QualType(Split.Ty, 0),
1802                         DS ? DS->getAtomicSpecLoc() : Loc);
1803     if (T.isNull())
1804       return T;
1805     Split.Quals.addCVRQualifiers(CVR);
1806     return BuildQualifiedType(T, Loc, Split.Quals);
1807   }
1808 
1809   Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1810   Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1811   return BuildQualifiedType(T, Loc, Q, DS);
1812 }
1813 
1814 /// Build a paren type including \p T.
1815 QualType Sema::BuildParenType(QualType T) {
1816   return Context.getParenType(T);
1817 }
1818 
1819 /// Given that we're building a pointer or reference to the given
1820 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1821                                            SourceLocation loc,
1822                                            bool isReference) {
1823   // Bail out if retention is unrequired or already specified.
1824   if (!type->isObjCLifetimeType() ||
1825       type.getObjCLifetime() != Qualifiers::OCL_None)
1826     return type;
1827 
1828   Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1829 
1830   // If the object type is const-qualified, we can safely use
1831   // __unsafe_unretained.  This is safe (because there are no read
1832   // barriers), and it'll be safe to coerce anything but __weak* to
1833   // the resulting type.
1834   if (type.isConstQualified()) {
1835     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1836 
1837   // Otherwise, check whether the static type does not require
1838   // retaining.  This currently only triggers for Class (possibly
1839   // protocol-qualifed, and arrays thereof).
1840   } else if (type->isObjCARCImplicitlyUnretainedType()) {
1841     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1842 
1843   // If we are in an unevaluated context, like sizeof, skip adding a
1844   // qualification.
1845   } else if (S.isUnevaluatedContext()) {
1846     return type;
1847 
1848   // If that failed, give an error and recover using __strong.  __strong
1849   // is the option most likely to prevent spurious second-order diagnostics,
1850   // like when binding a reference to a field.
1851   } else {
1852     // These types can show up in private ivars in system headers, so
1853     // we need this to not be an error in those cases.  Instead we
1854     // want to delay.
1855     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1856       S.DelayedDiagnostics.add(
1857           sema::DelayedDiagnostic::makeForbiddenType(loc,
1858               diag::err_arc_indirect_no_ownership, type, isReference));
1859     } else {
1860       S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1861     }
1862     implicitLifetime = Qualifiers::OCL_Strong;
1863   }
1864   assert(implicitLifetime && "didn't infer any lifetime!");
1865 
1866   Qualifiers qs;
1867   qs.addObjCLifetime(implicitLifetime);
1868   return S.Context.getQualifiedType(type, qs);
1869 }
1870 
1871 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1872   std::string Quals =
1873     Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1874 
1875   switch (FnTy->getRefQualifier()) {
1876   case RQ_None:
1877     break;
1878 
1879   case RQ_LValue:
1880     if (!Quals.empty())
1881       Quals += ' ';
1882     Quals += '&';
1883     break;
1884 
1885   case RQ_RValue:
1886     if (!Quals.empty())
1887       Quals += ' ';
1888     Quals += "&&";
1889     break;
1890   }
1891 
1892   return Quals;
1893 }
1894 
1895 namespace {
1896 /// Kinds of declarator that cannot contain a qualified function type.
1897 ///
1898 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1899 ///     a function type with a cv-qualifier or a ref-qualifier can only appear
1900 ///     at the topmost level of a type.
1901 ///
1902 /// Parens and member pointers are permitted. We don't diagnose array and
1903 /// function declarators, because they don't allow function types at all.
1904 ///
1905 /// The values of this enum are used in diagnostics.
1906 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1907 } // end anonymous namespace
1908 
1909 /// Check whether the type T is a qualified function type, and if it is,
1910 /// diagnose that it cannot be contained within the given kind of declarator.
1911 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1912                                    QualifiedFunctionKind QFK) {
1913   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1914   const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1915   if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1916     return false;
1917 
1918   S.Diag(Loc, diag::err_compound_qualified_function_type)
1919     << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1920     << getFunctionQualifiersAsString(FPT);
1921   return true;
1922 }
1923 
1924 /// Build a pointer type.
1925 ///
1926 /// \param T The type to which we'll be building a pointer.
1927 ///
1928 /// \param Loc The location of the entity whose type involves this
1929 /// pointer type or, if there is no such entity, the location of the
1930 /// type that will have pointer type.
1931 ///
1932 /// \param Entity The name of the entity that involves the pointer
1933 /// type, if known.
1934 ///
1935 /// \returns A suitable pointer type, if there are no
1936 /// errors. Otherwise, returns a NULL type.
1937 QualType Sema::BuildPointerType(QualType T,
1938                                 SourceLocation Loc, DeclarationName Entity) {
1939   if (T->isReferenceType()) {
1940     // C++ 8.3.2p4: There shall be no ... pointers to references ...
1941     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1942       << getPrintableNameForEntity(Entity) << T;
1943     return QualType();
1944   }
1945 
1946   if (T->isFunctionType() && getLangOpts().OpenCL) {
1947     Diag(Loc, diag::err_opencl_function_pointer);
1948     return QualType();
1949   }
1950 
1951   if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1952     return QualType();
1953 
1954   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1955 
1956   // In ARC, it is forbidden to build pointers to unqualified pointers.
1957   if (getLangOpts().ObjCAutoRefCount)
1958     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1959 
1960   // Build the pointer type.
1961   return Context.getPointerType(T);
1962 }
1963 
1964 /// Build a reference type.
1965 ///
1966 /// \param T The type to which we'll be building a reference.
1967 ///
1968 /// \param Loc The location of the entity whose type involves this
1969 /// reference type or, if there is no such entity, the location of the
1970 /// type that will have reference type.
1971 ///
1972 /// \param Entity The name of the entity that involves the reference
1973 /// type, if known.
1974 ///
1975 /// \returns A suitable reference type, if there are no
1976 /// errors. Otherwise, returns a NULL type.
1977 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1978                                   SourceLocation Loc,
1979                                   DeclarationName Entity) {
1980   assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1981          "Unresolved overloaded function type");
1982 
1983   // C++0x [dcl.ref]p6:
1984   //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1985   //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1986   //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1987   //   the type "lvalue reference to T", while an attempt to create the type
1988   //   "rvalue reference to cv TR" creates the type TR.
1989   bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1990 
1991   // C++ [dcl.ref]p4: There shall be no references to references.
1992   //
1993   // According to C++ DR 106, references to references are only
1994   // diagnosed when they are written directly (e.g., "int & &"),
1995   // but not when they happen via a typedef:
1996   //
1997   //   typedef int& intref;
1998   //   typedef intref& intref2;
1999   //
2000   // Parser::ParseDeclaratorInternal diagnoses the case where
2001   // references are written directly; here, we handle the
2002   // collapsing of references-to-references as described in C++0x.
2003   // DR 106 and 540 introduce reference-collapsing into C++98/03.
2004 
2005   // C++ [dcl.ref]p1:
2006   //   A declarator that specifies the type "reference to cv void"
2007   //   is ill-formed.
2008   if (T->isVoidType()) {
2009     Diag(Loc, diag::err_reference_to_void);
2010     return QualType();
2011   }
2012 
2013   if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2014     return QualType();
2015 
2016   // In ARC, it is forbidden to build references to unqualified pointers.
2017   if (getLangOpts().ObjCAutoRefCount)
2018     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2019 
2020   // Handle restrict on references.
2021   if (LValueRef)
2022     return Context.getLValueReferenceType(T, SpelledAsLValue);
2023   return Context.getRValueReferenceType(T);
2024 }
2025 
2026 /// Build a Read-only Pipe type.
2027 ///
2028 /// \param T The type to which we'll be building a Pipe.
2029 ///
2030 /// \param Loc We do not use it for now.
2031 ///
2032 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2033 /// NULL type.
2034 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2035   return Context.getReadPipeType(T);
2036 }
2037 
2038 /// Build a Write-only Pipe type.
2039 ///
2040 /// \param T The type to which we'll be building a Pipe.
2041 ///
2042 /// \param Loc We do not use it for now.
2043 ///
2044 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2045 /// NULL type.
2046 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2047   return Context.getWritePipeType(T);
2048 }
2049 
2050 /// Check whether the specified array size makes the array type a VLA.  If so,
2051 /// return true, if not, return the size of the array in SizeVal.
2052 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2053   // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2054   // (like gnu99, but not c99) accept any evaluatable value as an extension.
2055   class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2056   public:
2057     VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2058 
2059     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2060     }
2061 
2062     void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2063       S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2064     }
2065   } Diagnoser;
2066 
2067   return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2068                                            S.LangOpts.GNUMode ||
2069                                            S.LangOpts.OpenCL).isInvalid();
2070 }
2071 
2072 /// Build an array type.
2073 ///
2074 /// \param T The type of each element in the array.
2075 ///
2076 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2077 ///
2078 /// \param ArraySize Expression describing the size of the array.
2079 ///
2080 /// \param Brackets The range from the opening '[' to the closing ']'.
2081 ///
2082 /// \param Entity The name of the entity that involves the array
2083 /// type, if known.
2084 ///
2085 /// \returns A suitable array type, if there are no errors. Otherwise,
2086 /// returns a NULL type.
2087 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2088                               Expr *ArraySize, unsigned Quals,
2089                               SourceRange Brackets, DeclarationName Entity) {
2090 
2091   SourceLocation Loc = Brackets.getBegin();
2092   if (getLangOpts().CPlusPlus) {
2093     // C++ [dcl.array]p1:
2094     //   T is called the array element type; this type shall not be a reference
2095     //   type, the (possibly cv-qualified) type void, a function type or an
2096     //   abstract class type.
2097     //
2098     // C++ [dcl.array]p3:
2099     //   When several "array of" specifications are adjacent, [...] only the
2100     //   first of the constant expressions that specify the bounds of the arrays
2101     //   may be omitted.
2102     //
2103     // Note: function types are handled in the common path with C.
2104     if (T->isReferenceType()) {
2105       Diag(Loc, diag::err_illegal_decl_array_of_references)
2106       << getPrintableNameForEntity(Entity) << T;
2107       return QualType();
2108     }
2109 
2110     if (T->isVoidType() || T->isIncompleteArrayType()) {
2111       Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2112       return QualType();
2113     }
2114 
2115     if (RequireNonAbstractType(Brackets.getBegin(), T,
2116                                diag::err_array_of_abstract_type))
2117       return QualType();
2118 
2119     // Mentioning a member pointer type for an array type causes us to lock in
2120     // an inheritance model, even if it's inside an unused typedef.
2121     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2122       if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2123         if (!MPTy->getClass()->isDependentType())
2124           (void)isCompleteType(Loc, T);
2125 
2126   } else {
2127     // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2128     // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2129     if (RequireCompleteType(Loc, T,
2130                             diag::err_illegal_decl_array_incomplete_type))
2131       return QualType();
2132   }
2133 
2134   if (T->isFunctionType()) {
2135     Diag(Loc, diag::err_illegal_decl_array_of_functions)
2136       << getPrintableNameForEntity(Entity) << T;
2137     return QualType();
2138   }
2139 
2140   if (const RecordType *EltTy = T->getAs<RecordType>()) {
2141     // If the element type is a struct or union that contains a variadic
2142     // array, accept it as a GNU extension: C99 6.7.2.1p2.
2143     if (EltTy->getDecl()->hasFlexibleArrayMember())
2144       Diag(Loc, diag::ext_flexible_array_in_array) << T;
2145   } else if (T->isObjCObjectType()) {
2146     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2147     return QualType();
2148   }
2149 
2150   // Do placeholder conversions on the array size expression.
2151   if (ArraySize && ArraySize->hasPlaceholderType()) {
2152     ExprResult Result = CheckPlaceholderExpr(ArraySize);
2153     if (Result.isInvalid()) return QualType();
2154     ArraySize = Result.get();
2155   }
2156 
2157   // Do lvalue-to-rvalue conversions on the array size expression.
2158   if (ArraySize && !ArraySize->isRValue()) {
2159     ExprResult Result = DefaultLvalueConversion(ArraySize);
2160     if (Result.isInvalid())
2161       return QualType();
2162 
2163     ArraySize = Result.get();
2164   }
2165 
2166   // C99 6.7.5.2p1: The size expression shall have integer type.
2167   // C++11 allows contextual conversions to such types.
2168   if (!getLangOpts().CPlusPlus11 &&
2169       ArraySize && !ArraySize->isTypeDependent() &&
2170       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2171     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2172       << ArraySize->getType() << ArraySize->getSourceRange();
2173     return QualType();
2174   }
2175 
2176   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2177   if (!ArraySize) {
2178     if (ASM == ArrayType::Star)
2179       T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2180     else
2181       T = Context.getIncompleteArrayType(T, ASM, Quals);
2182   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2183     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2184   } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2185               !T->isConstantSizeType()) ||
2186              isArraySizeVLA(*this, ArraySize, ConstVal)) {
2187     // Even in C++11, don't allow contextual conversions in the array bound
2188     // of a VLA.
2189     if (getLangOpts().CPlusPlus11 &&
2190         !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2191       Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2192         << ArraySize->getType() << ArraySize->getSourceRange();
2193       return QualType();
2194     }
2195 
2196     // C99: an array with an element type that has a non-constant-size is a VLA.
2197     // C99: an array with a non-ICE size is a VLA.  We accept any expression
2198     // that we can fold to a non-zero positive value as an extension.
2199     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2200   } else {
2201     // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2202     // have a value greater than zero.
2203     if (ConstVal.isSigned() && ConstVal.isNegative()) {
2204       if (Entity)
2205         Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2206           << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2207       else
2208         Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2209           << ArraySize->getSourceRange();
2210       return QualType();
2211     }
2212     if (ConstVal == 0) {
2213       // GCC accepts zero sized static arrays. We allow them when
2214       // we're not in a SFINAE context.
2215       Diag(ArraySize->getLocStart(),
2216            isSFINAEContext()? diag::err_typecheck_zero_array_size
2217                             : diag::ext_typecheck_zero_array_size)
2218         << ArraySize->getSourceRange();
2219 
2220       if (ASM == ArrayType::Static) {
2221         Diag(ArraySize->getLocStart(),
2222              diag::warn_typecheck_zero_static_array_size)
2223           << ArraySize->getSourceRange();
2224         ASM = ArrayType::Normal;
2225       }
2226     } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2227                !T->isIncompleteType() && !T->isUndeducedType()) {
2228       // Is the array too large?
2229       unsigned ActiveSizeBits
2230         = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2231       if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2232         Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2233           << ConstVal.toString(10)
2234           << ArraySize->getSourceRange();
2235         return QualType();
2236       }
2237     }
2238 
2239     T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2240   }
2241 
2242   // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2243   if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2244     Diag(Loc, diag::err_opencl_vla);
2245     return QualType();
2246   }
2247 
2248   if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2249     if (getLangOpts().CUDA) {
2250       // CUDA device code doesn't support VLAs.
2251       CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget();
2252     } else if (!getLangOpts().OpenMP ||
2253                shouldDiagnoseTargetSupportFromOpenMP()) {
2254       // Some targets don't support VLAs.
2255       Diag(Loc, diag::err_vla_unsupported);
2256       return QualType();
2257     }
2258   }
2259 
2260   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2261   if (!getLangOpts().C99) {
2262     if (T->isVariableArrayType()) {
2263       // Prohibit the use of VLAs during template argument deduction.
2264       if (isSFINAEContext()) {
2265         Diag(Loc, diag::err_vla_in_sfinae);
2266         return QualType();
2267       }
2268       // Just extwarn about VLAs.
2269       else
2270         Diag(Loc, diag::ext_vla);
2271     } else if (ASM != ArrayType::Normal || Quals != 0)
2272       Diag(Loc,
2273            getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2274                                   : diag::ext_c99_array_usage) << ASM;
2275   }
2276 
2277   if (T->isVariableArrayType()) {
2278     // Warn about VLAs for -Wvla.
2279     Diag(Loc, diag::warn_vla_used);
2280   }
2281 
2282   // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2283   // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2284   // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2285   if (getLangOpts().OpenCL) {
2286     const QualType ArrType = Context.getBaseElementType(T);
2287     if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2288         ArrType->isSamplerT() || ArrType->isImageType()) {
2289       Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2290       return QualType();
2291     }
2292   }
2293 
2294   return T;
2295 }
2296 
2297 /// Build an ext-vector type.
2298 ///
2299 /// Run the required checks for the extended vector type.
2300 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2301                                   SourceLocation AttrLoc) {
2302   // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2303   // in conjunction with complex types (pointers, arrays, functions, etc.).
2304   //
2305   // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2306   // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2307   // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2308   // of bool aren't allowed.
2309   if ((!T->isDependentType() && !T->isIntegerType() &&
2310        !T->isRealFloatingType()) ||
2311       T->isBooleanType()) {
2312     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2313     return QualType();
2314   }
2315 
2316   if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2317     llvm::APSInt vecSize(32);
2318     if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2319       Diag(AttrLoc, diag::err_attribute_argument_type)
2320         << "ext_vector_type" << AANT_ArgumentIntegerConstant
2321         << ArraySize->getSourceRange();
2322       return QualType();
2323     }
2324 
2325     // Unlike gcc's vector_size attribute, the size is specified as the
2326     // number of elements, not the number of bytes.
2327     unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2328 
2329     if (vectorSize == 0) {
2330       Diag(AttrLoc, diag::err_attribute_zero_size)
2331       << ArraySize->getSourceRange();
2332       return QualType();
2333     }
2334 
2335     if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2336       Diag(AttrLoc, diag::err_attribute_size_too_large)
2337         << ArraySize->getSourceRange();
2338       return QualType();
2339     }
2340 
2341     return Context.getExtVectorType(T, vectorSize);
2342   }
2343 
2344   return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2345 }
2346 
2347 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2348   if (T->isArrayType() || T->isFunctionType()) {
2349     Diag(Loc, diag::err_func_returning_array_function)
2350       << T->isFunctionType() << T;
2351     return true;
2352   }
2353 
2354   // Functions cannot return half FP.
2355   if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2356     Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2357       FixItHint::CreateInsertion(Loc, "*");
2358     return true;
2359   }
2360 
2361   // Methods cannot return interface types. All ObjC objects are
2362   // passed by reference.
2363   if (T->isObjCObjectType()) {
2364     Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2365         << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2366     return true;
2367   }
2368 
2369   return false;
2370 }
2371 
2372 /// Check the extended parameter information.  Most of the necessary
2373 /// checking should occur when applying the parameter attribute; the
2374 /// only other checks required are positional restrictions.
2375 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2376                     const FunctionProtoType::ExtProtoInfo &EPI,
2377                     llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2378   assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2379 
2380   bool hasCheckedSwiftCall = false;
2381   auto checkForSwiftCC = [&](unsigned paramIndex) {
2382     // Only do this once.
2383     if (hasCheckedSwiftCall) return;
2384     hasCheckedSwiftCall = true;
2385     if (EPI.ExtInfo.getCC() == CC_Swift) return;
2386     S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2387       << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2388   };
2389 
2390   for (size_t paramIndex = 0, numParams = paramTypes.size();
2391           paramIndex != numParams; ++paramIndex) {
2392     switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2393     // Nothing interesting to check for orindary-ABI parameters.
2394     case ParameterABI::Ordinary:
2395       continue;
2396 
2397     // swift_indirect_result parameters must be a prefix of the function
2398     // arguments.
2399     case ParameterABI::SwiftIndirectResult:
2400       checkForSwiftCC(paramIndex);
2401       if (paramIndex != 0 &&
2402           EPI.ExtParameterInfos[paramIndex - 1].getABI()
2403             != ParameterABI::SwiftIndirectResult) {
2404         S.Diag(getParamLoc(paramIndex),
2405                diag::err_swift_indirect_result_not_first);
2406       }
2407       continue;
2408 
2409     case ParameterABI::SwiftContext:
2410       checkForSwiftCC(paramIndex);
2411       continue;
2412 
2413     // swift_error parameters must be preceded by a swift_context parameter.
2414     case ParameterABI::SwiftErrorResult:
2415       checkForSwiftCC(paramIndex);
2416       if (paramIndex == 0 ||
2417           EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2418               ParameterABI::SwiftContext) {
2419         S.Diag(getParamLoc(paramIndex),
2420                diag::err_swift_error_result_not_after_swift_context);
2421       }
2422       continue;
2423     }
2424     llvm_unreachable("bad ABI kind");
2425   }
2426 }
2427 
2428 QualType Sema::BuildFunctionType(QualType T,
2429                                  MutableArrayRef<QualType> ParamTypes,
2430                                  SourceLocation Loc, DeclarationName Entity,
2431                                  const FunctionProtoType::ExtProtoInfo &EPI) {
2432   bool Invalid = false;
2433 
2434   Invalid |= CheckFunctionReturnType(T, Loc);
2435 
2436   for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2437     // FIXME: Loc is too inprecise here, should use proper locations for args.
2438     QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2439     if (ParamType->isVoidType()) {
2440       Diag(Loc, diag::err_param_with_void_type);
2441       Invalid = true;
2442     } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2443       // Disallow half FP arguments.
2444       Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2445         FixItHint::CreateInsertion(Loc, "*");
2446       Invalid = true;
2447     }
2448 
2449     ParamTypes[Idx] = ParamType;
2450   }
2451 
2452   if (EPI.ExtParameterInfos) {
2453     checkExtParameterInfos(*this, ParamTypes, EPI,
2454                            [=](unsigned i) { return Loc; });
2455   }
2456 
2457   if (EPI.ExtInfo.getProducesResult()) {
2458     // This is just a warning, so we can't fail to build if we see it.
2459     checkNSReturnsRetainedReturnType(Loc, T);
2460   }
2461 
2462   if (Invalid)
2463     return QualType();
2464 
2465   return Context.getFunctionType(T, ParamTypes, EPI);
2466 }
2467 
2468 /// Build a member pointer type \c T Class::*.
2469 ///
2470 /// \param T the type to which the member pointer refers.
2471 /// \param Class the class type into which the member pointer points.
2472 /// \param Loc the location where this type begins
2473 /// \param Entity the name of the entity that will have this member pointer type
2474 ///
2475 /// \returns a member pointer type, if successful, or a NULL type if there was
2476 /// an error.
2477 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2478                                       SourceLocation Loc,
2479                                       DeclarationName Entity) {
2480   // Verify that we're not building a pointer to pointer to function with
2481   // exception specification.
2482   if (CheckDistantExceptionSpec(T)) {
2483     Diag(Loc, diag::err_distant_exception_spec);
2484     return QualType();
2485   }
2486 
2487   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2488   //   with reference type, or "cv void."
2489   if (T->isReferenceType()) {
2490     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2491       << getPrintableNameForEntity(Entity) << T;
2492     return QualType();
2493   }
2494 
2495   if (T->isVoidType()) {
2496     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2497       << getPrintableNameForEntity(Entity);
2498     return QualType();
2499   }
2500 
2501   if (!Class->isDependentType() && !Class->isRecordType()) {
2502     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2503     return QualType();
2504   }
2505 
2506   // Adjust the default free function calling convention to the default method
2507   // calling convention.
2508   bool IsCtorOrDtor =
2509       (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2510       (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2511   if (T->isFunctionType())
2512     adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2513 
2514   return Context.getMemberPointerType(T, Class.getTypePtr());
2515 }
2516 
2517 /// Build a block pointer type.
2518 ///
2519 /// \param T The type to which we'll be building a block pointer.
2520 ///
2521 /// \param Loc The source location, used for diagnostics.
2522 ///
2523 /// \param Entity The name of the entity that involves the block pointer
2524 /// type, if known.
2525 ///
2526 /// \returns A suitable block pointer type, if there are no
2527 /// errors. Otherwise, returns a NULL type.
2528 QualType Sema::BuildBlockPointerType(QualType T,
2529                                      SourceLocation Loc,
2530                                      DeclarationName Entity) {
2531   if (!T->isFunctionType()) {
2532     Diag(Loc, diag::err_nonfunction_block_type);
2533     return QualType();
2534   }
2535 
2536   if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2537     return QualType();
2538 
2539   return Context.getBlockPointerType(T);
2540 }
2541 
2542 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2543   QualType QT = Ty.get();
2544   if (QT.isNull()) {
2545     if (TInfo) *TInfo = nullptr;
2546     return QualType();
2547   }
2548 
2549   TypeSourceInfo *DI = nullptr;
2550   if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2551     QT = LIT->getType();
2552     DI = LIT->getTypeSourceInfo();
2553   }
2554 
2555   if (TInfo) *TInfo = DI;
2556   return QT;
2557 }
2558 
2559 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2560                                             Qualifiers::ObjCLifetime ownership,
2561                                             unsigned chunkIndex);
2562 
2563 /// Given that this is the declaration of a parameter under ARC,
2564 /// attempt to infer attributes and such for pointer-to-whatever
2565 /// types.
2566 static void inferARCWriteback(TypeProcessingState &state,
2567                               QualType &declSpecType) {
2568   Sema &S = state.getSema();
2569   Declarator &declarator = state.getDeclarator();
2570 
2571   // TODO: should we care about decl qualifiers?
2572 
2573   // Check whether the declarator has the expected form.  We walk
2574   // from the inside out in order to make the block logic work.
2575   unsigned outermostPointerIndex = 0;
2576   bool isBlockPointer = false;
2577   unsigned numPointers = 0;
2578   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2579     unsigned chunkIndex = i;
2580     DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2581     switch (chunk.Kind) {
2582     case DeclaratorChunk::Paren:
2583       // Ignore parens.
2584       break;
2585 
2586     case DeclaratorChunk::Reference:
2587     case DeclaratorChunk::Pointer:
2588       // Count the number of pointers.  Treat references
2589       // interchangeably as pointers; if they're mis-ordered, normal
2590       // type building will discover that.
2591       outermostPointerIndex = chunkIndex;
2592       numPointers++;
2593       break;
2594 
2595     case DeclaratorChunk::BlockPointer:
2596       // If we have a pointer to block pointer, that's an acceptable
2597       // indirect reference; anything else is not an application of
2598       // the rules.
2599       if (numPointers != 1) return;
2600       numPointers++;
2601       outermostPointerIndex = chunkIndex;
2602       isBlockPointer = true;
2603 
2604       // We don't care about pointer structure in return values here.
2605       goto done;
2606 
2607     case DeclaratorChunk::Array: // suppress if written (id[])?
2608     case DeclaratorChunk::Function:
2609     case DeclaratorChunk::MemberPointer:
2610     case DeclaratorChunk::Pipe:
2611       return;
2612     }
2613   }
2614  done:
2615 
2616   // If we have *one* pointer, then we want to throw the qualifier on
2617   // the declaration-specifiers, which means that it needs to be a
2618   // retainable object type.
2619   if (numPointers == 1) {
2620     // If it's not a retainable object type, the rule doesn't apply.
2621     if (!declSpecType->isObjCRetainableType()) return;
2622 
2623     // If it already has lifetime, don't do anything.
2624     if (declSpecType.getObjCLifetime()) return;
2625 
2626     // Otherwise, modify the type in-place.
2627     Qualifiers qs;
2628 
2629     if (declSpecType->isObjCARCImplicitlyUnretainedType())
2630       qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2631     else
2632       qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2633     declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2634 
2635   // If we have *two* pointers, then we want to throw the qualifier on
2636   // the outermost pointer.
2637   } else if (numPointers == 2) {
2638     // If we don't have a block pointer, we need to check whether the
2639     // declaration-specifiers gave us something that will turn into a
2640     // retainable object pointer after we slap the first pointer on it.
2641     if (!isBlockPointer && !declSpecType->isObjCObjectType())
2642       return;
2643 
2644     // Look for an explicit lifetime attribute there.
2645     DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2646     if (chunk.Kind != DeclaratorChunk::Pointer &&
2647         chunk.Kind != DeclaratorChunk::BlockPointer)
2648       return;
2649     for (const AttributeList *attr = chunk.getAttrs(); attr;
2650            attr = attr->getNext())
2651       if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2652         return;
2653 
2654     transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2655                                           outermostPointerIndex);
2656 
2657   // Any other number of pointers/references does not trigger the rule.
2658   } else return;
2659 
2660   // TODO: mark whether we did this inference?
2661 }
2662 
2663 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2664                                      SourceLocation FallbackLoc,
2665                                      SourceLocation ConstQualLoc,
2666                                      SourceLocation VolatileQualLoc,
2667                                      SourceLocation RestrictQualLoc,
2668                                      SourceLocation AtomicQualLoc,
2669                                      SourceLocation UnalignedQualLoc) {
2670   if (!Quals)
2671     return;
2672 
2673   struct Qual {
2674     const char *Name;
2675     unsigned Mask;
2676     SourceLocation Loc;
2677   } const QualKinds[5] = {
2678     { "const", DeclSpec::TQ_const, ConstQualLoc },
2679     { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2680     { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2681     { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2682     { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2683   };
2684 
2685   SmallString<32> QualStr;
2686   unsigned NumQuals = 0;
2687   SourceLocation Loc;
2688   FixItHint FixIts[5];
2689 
2690   // Build a string naming the redundant qualifiers.
2691   for (auto &E : QualKinds) {
2692     if (Quals & E.Mask) {
2693       if (!QualStr.empty()) QualStr += ' ';
2694       QualStr += E.Name;
2695 
2696       // If we have a location for the qualifier, offer a fixit.
2697       SourceLocation QualLoc = E.Loc;
2698       if (QualLoc.isValid()) {
2699         FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2700         if (Loc.isInvalid() ||
2701             getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2702           Loc = QualLoc;
2703       }
2704 
2705       ++NumQuals;
2706     }
2707   }
2708 
2709   Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2710     << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2711 }
2712 
2713 // Diagnose pointless type qualifiers on the return type of a function.
2714 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2715                                                   Declarator &D,
2716                                                   unsigned FunctionChunkIndex) {
2717   if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2718     // FIXME: TypeSourceInfo doesn't preserve location information for
2719     // qualifiers.
2720     S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2721                                 RetTy.getLocalCVRQualifiers(),
2722                                 D.getIdentifierLoc());
2723     return;
2724   }
2725 
2726   for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2727                 End = D.getNumTypeObjects();
2728        OuterChunkIndex != End; ++OuterChunkIndex) {
2729     DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2730     switch (OuterChunk.Kind) {
2731     case DeclaratorChunk::Paren:
2732       continue;
2733 
2734     case DeclaratorChunk::Pointer: {
2735       DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2736       S.diagnoseIgnoredQualifiers(
2737           diag::warn_qual_return_type,
2738           PTI.TypeQuals,
2739           SourceLocation(),
2740           SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2741           SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2742           SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2743           SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2744           SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2745       return;
2746     }
2747 
2748     case DeclaratorChunk::Function:
2749     case DeclaratorChunk::BlockPointer:
2750     case DeclaratorChunk::Reference:
2751     case DeclaratorChunk::Array:
2752     case DeclaratorChunk::MemberPointer:
2753     case DeclaratorChunk::Pipe:
2754       // FIXME: We can't currently provide an accurate source location and a
2755       // fix-it hint for these.
2756       unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2757       S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2758                                   RetTy.getCVRQualifiers() | AtomicQual,
2759                                   D.getIdentifierLoc());
2760       return;
2761     }
2762 
2763     llvm_unreachable("unknown declarator chunk kind");
2764   }
2765 
2766   // If the qualifiers come from a conversion function type, don't diagnose
2767   // them -- they're not necessarily redundant, since such a conversion
2768   // operator can be explicitly called as "x.operator const int()".
2769   if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
2770     return;
2771 
2772   // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2773   // which are present there.
2774   S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2775                               D.getDeclSpec().getTypeQualifiers(),
2776                               D.getIdentifierLoc(),
2777                               D.getDeclSpec().getConstSpecLoc(),
2778                               D.getDeclSpec().getVolatileSpecLoc(),
2779                               D.getDeclSpec().getRestrictSpecLoc(),
2780                               D.getDeclSpec().getAtomicSpecLoc(),
2781                               D.getDeclSpec().getUnalignedSpecLoc());
2782 }
2783 
2784 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2785                                              TypeSourceInfo *&ReturnTypeInfo) {
2786   Sema &SemaRef = state.getSema();
2787   Declarator &D = state.getDeclarator();
2788   QualType T;
2789   ReturnTypeInfo = nullptr;
2790 
2791   // The TagDecl owned by the DeclSpec.
2792   TagDecl *OwnedTagDecl = nullptr;
2793 
2794   switch (D.getName().getKind()) {
2795   case UnqualifiedIdKind::IK_ImplicitSelfParam:
2796   case UnqualifiedIdKind::IK_OperatorFunctionId:
2797   case UnqualifiedIdKind::IK_Identifier:
2798   case UnqualifiedIdKind::IK_LiteralOperatorId:
2799   case UnqualifiedIdKind::IK_TemplateId:
2800     T = ConvertDeclSpecToType(state);
2801 
2802     if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2803       OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2804       // Owned declaration is embedded in declarator.
2805       OwnedTagDecl->setEmbeddedInDeclarator(true);
2806     }
2807     break;
2808 
2809   case UnqualifiedIdKind::IK_ConstructorName:
2810   case UnqualifiedIdKind::IK_ConstructorTemplateId:
2811   case UnqualifiedIdKind::IK_DestructorName:
2812     // Constructors and destructors don't have return types. Use
2813     // "void" instead.
2814     T = SemaRef.Context.VoidTy;
2815     processTypeAttrs(state, T, TAL_DeclSpec,
2816                      D.getDeclSpec().getAttributes().getList());
2817     break;
2818 
2819   case UnqualifiedIdKind::IK_DeductionGuideName:
2820     // Deduction guides have a trailing return type and no type in their
2821     // decl-specifier sequence. Use a placeholder return type for now.
2822     T = SemaRef.Context.DependentTy;
2823     break;
2824 
2825   case UnqualifiedIdKind::IK_ConversionFunctionId:
2826     // The result type of a conversion function is the type that it
2827     // converts to.
2828     T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2829                                   &ReturnTypeInfo);
2830     break;
2831   }
2832 
2833   if (D.getAttributes())
2834     distributeTypeAttrsFromDeclarator(state, T);
2835 
2836   // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2837   if (DeducedType *Deduced = T->getContainedDeducedType()) {
2838     AutoType *Auto = dyn_cast<AutoType>(Deduced);
2839     int Error = -1;
2840 
2841     // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2842     // class template argument deduction)?
2843     bool IsCXXAutoType =
2844         (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2845 
2846     switch (D.getContext()) {
2847     case DeclaratorContext::LambdaExprContext:
2848       // Declared return type of a lambda-declarator is implicit and is always
2849       // 'auto'.
2850       break;
2851     case DeclaratorContext::ObjCParameterContext:
2852     case DeclaratorContext::ObjCResultContext:
2853     case DeclaratorContext::PrototypeContext:
2854       Error = 0;
2855       break;
2856     case DeclaratorContext::LambdaExprParameterContext:
2857       // In C++14, generic lambdas allow 'auto' in their parameters.
2858       if (!SemaRef.getLangOpts().CPlusPlus14 ||
2859           !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2860         Error = 16;
2861       else {
2862         // If auto is mentioned in a lambda parameter context, convert it to a
2863         // template parameter type.
2864         sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2865         assert(LSI && "No LambdaScopeInfo on the stack!");
2866         const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2867         const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
2868         const bool IsParameterPack = D.hasEllipsis();
2869 
2870         // Create the TemplateTypeParmDecl here to retrieve the corresponding
2871         // template parameter type. Template parameters are temporarily added
2872         // to the TU until the associated TemplateDecl is created.
2873         TemplateTypeParmDecl *CorrespondingTemplateParam =
2874             TemplateTypeParmDecl::Create(
2875                 SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2876                 /*KeyLoc*/SourceLocation(), /*NameLoc*/D.getLocStart(),
2877                 TemplateParameterDepth, AutoParameterPosition,
2878                 /*Identifier*/nullptr, false, IsParameterPack);
2879         LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
2880         // Replace the 'auto' in the function parameter with this invented
2881         // template type parameter.
2882         // FIXME: Retain some type sugar to indicate that this was written
2883         // as 'auto'.
2884         T = SemaRef.ReplaceAutoType(
2885             T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2886       }
2887       break;
2888     case DeclaratorContext::MemberContext: {
2889       if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2890           D.isFunctionDeclarator())
2891         break;
2892       bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2893       switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2894       case TTK_Enum: llvm_unreachable("unhandled tag kind");
2895       case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2896       case TTK_Union:  Error = Cxx ? 3 : 4; /* Union member */ break;
2897       case TTK_Class:  Error = 5; /* Class member */ break;
2898       case TTK_Interface: Error = 6; /* Interface member */ break;
2899       }
2900       if (D.getDeclSpec().isFriendSpecified())
2901         Error = 20; // Friend type
2902       break;
2903     }
2904     case DeclaratorContext::CXXCatchContext:
2905     case DeclaratorContext::ObjCCatchContext:
2906       Error = 7; // Exception declaration
2907       break;
2908     case DeclaratorContext::TemplateParamContext:
2909       if (isa<DeducedTemplateSpecializationType>(Deduced))
2910         Error = 19; // Template parameter
2911       else if (!SemaRef.getLangOpts().CPlusPlus17)
2912         Error = 8; // Template parameter (until C++17)
2913       break;
2914     case DeclaratorContext::BlockLiteralContext:
2915       Error = 9; // Block literal
2916       break;
2917     case DeclaratorContext::TemplateArgContext:
2918       // Within a template argument list, a deduced template specialization
2919       // type will be reinterpreted as a template template argument.
2920       if (isa<DeducedTemplateSpecializationType>(Deduced) &&
2921           !D.getNumTypeObjects() &&
2922           D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
2923         break;
2924       LLVM_FALLTHROUGH;
2925     case DeclaratorContext::TemplateTypeArgContext:
2926       Error = 10; // Template type argument
2927       break;
2928     case DeclaratorContext::AliasDeclContext:
2929     case DeclaratorContext::AliasTemplateContext:
2930       Error = 12; // Type alias
2931       break;
2932     case DeclaratorContext::TrailingReturnContext:
2933     case DeclaratorContext::TrailingReturnVarContext:
2934       if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2935         Error = 13; // Function return type
2936       break;
2937     case DeclaratorContext::ConversionIdContext:
2938       if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2939         Error = 14; // conversion-type-id
2940       break;
2941     case DeclaratorContext::FunctionalCastContext:
2942       if (isa<DeducedTemplateSpecializationType>(Deduced))
2943         break;
2944       LLVM_FALLTHROUGH;
2945     case DeclaratorContext::TypeNameContext:
2946       Error = 15; // Generic
2947       break;
2948     case DeclaratorContext::FileContext:
2949     case DeclaratorContext::BlockContext:
2950     case DeclaratorContext::ForContext:
2951     case DeclaratorContext::InitStmtContext:
2952     case DeclaratorContext::ConditionContext:
2953       // FIXME: P0091R3 (erroneously) does not permit class template argument
2954       // deduction in conditions, for-init-statements, and other declarations
2955       // that are not simple-declarations.
2956       break;
2957     case DeclaratorContext::CXXNewContext:
2958       // FIXME: P0091R3 does not permit class template argument deduction here,
2959       // but we follow GCC and allow it anyway.
2960       if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
2961         Error = 17; // 'new' type
2962       break;
2963     case DeclaratorContext::KNRTypeListContext:
2964       Error = 18; // K&R function parameter
2965       break;
2966     }
2967 
2968     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2969       Error = 11;
2970 
2971     // In Objective-C it is an error to use 'auto' on a function declarator
2972     // (and everywhere for '__auto_type').
2973     if (D.isFunctionDeclarator() &&
2974         (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
2975       Error = 13;
2976 
2977     bool HaveTrailing = false;
2978 
2979     // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2980     // contains a trailing return type. That is only legal at the outermost
2981     // level. Check all declarator chunks (outermost first) anyway, to give
2982     // better diagnostics.
2983     // We don't support '__auto_type' with trailing return types.
2984     // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
2985     if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
2986         D.hasTrailingReturnType()) {
2987       HaveTrailing = true;
2988       Error = -1;
2989     }
2990 
2991     SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2992     if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
2993       AutoRange = D.getName().getSourceRange();
2994 
2995     if (Error != -1) {
2996       unsigned Kind;
2997       if (Auto) {
2998         switch (Auto->getKeyword()) {
2999         case AutoTypeKeyword::Auto: Kind = 0; break;
3000         case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3001         case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3002         }
3003       } else {
3004         assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3005                "unknown auto type");
3006         Kind = 3;
3007       }
3008 
3009       auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3010       TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3011 
3012       SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3013         << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3014         << QualType(Deduced, 0) << AutoRange;
3015       if (auto *TD = TN.getAsTemplateDecl())
3016         SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3017 
3018       T = SemaRef.Context.IntTy;
3019       D.setInvalidType(true);
3020     } else if (!HaveTrailing &&
3021                D.getContext() != DeclaratorContext::LambdaExprContext) {
3022       // If there was a trailing return type, we already got
3023       // warn_cxx98_compat_trailing_return_type in the parser.
3024       // If this was a lambda, we already warned on that too.
3025       SemaRef.Diag(AutoRange.getBegin(),
3026                    diag::warn_cxx98_compat_auto_type_specifier)
3027         << AutoRange;
3028     }
3029   }
3030 
3031   if (SemaRef.getLangOpts().CPlusPlus &&
3032       OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3033     // Check the contexts where C++ forbids the declaration of a new class
3034     // or enumeration in a type-specifier-seq.
3035     unsigned DiagID = 0;
3036     switch (D.getContext()) {
3037     case DeclaratorContext::TrailingReturnContext:
3038     case DeclaratorContext::TrailingReturnVarContext:
3039       // Class and enumeration definitions are syntactically not allowed in
3040       // trailing return types.
3041       llvm_unreachable("parser should not have allowed this");
3042       break;
3043     case DeclaratorContext::FileContext:
3044     case DeclaratorContext::MemberContext:
3045     case DeclaratorContext::BlockContext:
3046     case DeclaratorContext::ForContext:
3047     case DeclaratorContext::InitStmtContext:
3048     case DeclaratorContext::BlockLiteralContext:
3049     case DeclaratorContext::LambdaExprContext:
3050       // C++11 [dcl.type]p3:
3051       //   A type-specifier-seq shall not define a class or enumeration unless
3052       //   it appears in the type-id of an alias-declaration (7.1.3) that is not
3053       //   the declaration of a template-declaration.
3054     case DeclaratorContext::AliasDeclContext:
3055       break;
3056     case DeclaratorContext::AliasTemplateContext:
3057       DiagID = diag::err_type_defined_in_alias_template;
3058       break;
3059     case DeclaratorContext::TypeNameContext:
3060     case DeclaratorContext::FunctionalCastContext:
3061     case DeclaratorContext::ConversionIdContext:
3062     case DeclaratorContext::TemplateParamContext:
3063     case DeclaratorContext::CXXNewContext:
3064     case DeclaratorContext::CXXCatchContext:
3065     case DeclaratorContext::ObjCCatchContext:
3066     case DeclaratorContext::TemplateArgContext:
3067     case DeclaratorContext::TemplateTypeArgContext:
3068       DiagID = diag::err_type_defined_in_type_specifier;
3069       break;
3070     case DeclaratorContext::PrototypeContext:
3071     case DeclaratorContext::LambdaExprParameterContext:
3072     case DeclaratorContext::ObjCParameterContext:
3073     case DeclaratorContext::ObjCResultContext:
3074     case DeclaratorContext::KNRTypeListContext:
3075       // C++ [dcl.fct]p6:
3076       //   Types shall not be defined in return or parameter types.
3077       DiagID = diag::err_type_defined_in_param_type;
3078       break;
3079     case DeclaratorContext::ConditionContext:
3080       // C++ 6.4p2:
3081       // The type-specifier-seq shall not contain typedef and shall not declare
3082       // a new class or enumeration.
3083       DiagID = diag::err_type_defined_in_condition;
3084       break;
3085     }
3086 
3087     if (DiagID != 0) {
3088       SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3089           << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3090       D.setInvalidType(true);
3091     }
3092   }
3093 
3094   assert(!T.isNull() && "This function should not return a null type");
3095   return T;
3096 }
3097 
3098 /// Produce an appropriate diagnostic for an ambiguity between a function
3099 /// declarator and a C++ direct-initializer.
3100 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3101                                        DeclaratorChunk &DeclType, QualType RT) {
3102   const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3103   assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3104 
3105   // If the return type is void there is no ambiguity.
3106   if (RT->isVoidType())
3107     return;
3108 
3109   // An initializer for a non-class type can have at most one argument.
3110   if (!RT->isRecordType() && FTI.NumParams > 1)
3111     return;
3112 
3113   // An initializer for a reference must have exactly one argument.
3114   if (RT->isReferenceType() && FTI.NumParams != 1)
3115     return;
3116 
3117   // Only warn if this declarator is declaring a function at block scope, and
3118   // doesn't have a storage class (such as 'extern') specified.
3119   if (!D.isFunctionDeclarator() ||
3120       D.getFunctionDefinitionKind() != FDK_Declaration ||
3121       !S.CurContext->isFunctionOrMethod() ||
3122       D.getDeclSpec().getStorageClassSpec()
3123         != DeclSpec::SCS_unspecified)
3124     return;
3125 
3126   // Inside a condition, a direct initializer is not permitted. We allow one to
3127   // be parsed in order to give better diagnostics in condition parsing.
3128   if (D.getContext() == DeclaratorContext::ConditionContext)
3129     return;
3130 
3131   SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3132 
3133   S.Diag(DeclType.Loc,
3134          FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3135                        : diag::warn_empty_parens_are_function_decl)
3136       << ParenRange;
3137 
3138   // If the declaration looks like:
3139   //   T var1,
3140   //   f();
3141   // and name lookup finds a function named 'f', then the ',' was
3142   // probably intended to be a ';'.
3143   if (!D.isFirstDeclarator() && D.getIdentifier()) {
3144     FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3145     FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3146     if (Comma.getFileID() != Name.getFileID() ||
3147         Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3148       LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3149                           Sema::LookupOrdinaryName);
3150       if (S.LookupName(Result, S.getCurScope()))
3151         S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3152           << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3153           << D.getIdentifier();
3154       Result.suppressDiagnostics();
3155     }
3156   }
3157 
3158   if (FTI.NumParams > 0) {
3159     // For a declaration with parameters, eg. "T var(T());", suggest adding
3160     // parens around the first parameter to turn the declaration into a
3161     // variable declaration.
3162     SourceRange Range = FTI.Params[0].Param->getSourceRange();
3163     SourceLocation B = Range.getBegin();
3164     SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3165     // FIXME: Maybe we should suggest adding braces instead of parens
3166     // in C++11 for classes that don't have an initializer_list constructor.
3167     S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3168       << FixItHint::CreateInsertion(B, "(")
3169       << FixItHint::CreateInsertion(E, ")");
3170   } else {
3171     // For a declaration without parameters, eg. "T var();", suggest replacing
3172     // the parens with an initializer to turn the declaration into a variable
3173     // declaration.
3174     const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3175 
3176     // Empty parens mean value-initialization, and no parens mean
3177     // default initialization. These are equivalent if the default
3178     // constructor is user-provided or if zero-initialization is a
3179     // no-op.
3180     if (RD && RD->hasDefinition() &&
3181         (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3182       S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3183         << FixItHint::CreateRemoval(ParenRange);
3184     else {
3185       std::string Init =
3186           S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3187       if (Init.empty() && S.LangOpts.CPlusPlus11)
3188         Init = "{}";
3189       if (!Init.empty())
3190         S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3191           << FixItHint::CreateReplacement(ParenRange, Init);
3192     }
3193   }
3194 }
3195 
3196 /// Produce an appropriate diagnostic for a declarator with top-level
3197 /// parentheses.
3198 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3199   DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3200   assert(Paren.Kind == DeclaratorChunk::Paren &&
3201          "do not have redundant top-level parentheses");
3202 
3203   // This is a syntactic check; we're not interested in cases that arise
3204   // during template instantiation.
3205   if (S.inTemplateInstantiation())
3206     return;
3207 
3208   // Check whether this could be intended to be a construction of a temporary
3209   // object in C++ via a function-style cast.
3210   bool CouldBeTemporaryObject =
3211       S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3212       !D.isInvalidType() && D.getIdentifier() &&
3213       D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3214       (T->isRecordType() || T->isDependentType()) &&
3215       D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3216 
3217   bool StartsWithDeclaratorId = true;
3218   for (auto &C : D.type_objects()) {
3219     switch (C.Kind) {
3220     case DeclaratorChunk::Paren:
3221       if (&C == &Paren)
3222         continue;
3223       LLVM_FALLTHROUGH;
3224     case DeclaratorChunk::Pointer:
3225       StartsWithDeclaratorId = false;
3226       continue;
3227 
3228     case DeclaratorChunk::Array:
3229       if (!C.Arr.NumElts)
3230         CouldBeTemporaryObject = false;
3231       continue;
3232 
3233     case DeclaratorChunk::Reference:
3234       // FIXME: Suppress the warning here if there is no initializer; we're
3235       // going to give an error anyway.
3236       // We assume that something like 'T (&x) = y;' is highly likely to not
3237       // be intended to be a temporary object.
3238       CouldBeTemporaryObject = false;
3239       StartsWithDeclaratorId = false;
3240       continue;
3241 
3242     case DeclaratorChunk::Function:
3243       // In a new-type-id, function chunks require parentheses.
3244       if (D.getContext() == DeclaratorContext::CXXNewContext)
3245         return;
3246       // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3247       // redundant-parens warning, but we don't know whether the function
3248       // chunk was syntactically valid as an expression here.
3249       CouldBeTemporaryObject = false;
3250       continue;
3251 
3252     case DeclaratorChunk::BlockPointer:
3253     case DeclaratorChunk::MemberPointer:
3254     case DeclaratorChunk::Pipe:
3255       // These cannot appear in expressions.
3256       CouldBeTemporaryObject = false;
3257       StartsWithDeclaratorId = false;
3258       continue;
3259     }
3260   }
3261 
3262   // FIXME: If there is an initializer, assume that this is not intended to be
3263   // a construction of a temporary object.
3264 
3265   // Check whether the name has already been declared; if not, this is not a
3266   // function-style cast.
3267   if (CouldBeTemporaryObject) {
3268     LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3269                         Sema::LookupOrdinaryName);
3270     if (!S.LookupName(Result, S.getCurScope()))
3271       CouldBeTemporaryObject = false;
3272     Result.suppressDiagnostics();
3273   }
3274 
3275   SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3276 
3277   if (!CouldBeTemporaryObject) {
3278     // If we have A (::B), the parentheses affect the meaning of the program.
3279     // Suppress the warning in that case. Don't bother looking at the DeclSpec
3280     // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3281     // formally unambiguous.
3282     if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3283       for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3284            NNS = NNS->getPrefix()) {
3285         if (NNS->getKind() == NestedNameSpecifier::Global)
3286           return;
3287       }
3288     }
3289 
3290     S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3291         << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3292         << FixItHint::CreateRemoval(Paren.EndLoc);
3293     return;
3294   }
3295 
3296   S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3297       << ParenRange << D.getIdentifier();
3298   auto *RD = T->getAsCXXRecordDecl();
3299   if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3300     S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3301         << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3302         << D.getIdentifier();
3303   // FIXME: A cast to void is probably a better suggestion in cases where it's
3304   // valid (when there is no initializer and we're not in a condition).
3305   S.Diag(D.getLocStart(), diag::note_function_style_cast_add_parentheses)
3306       << FixItHint::CreateInsertion(D.getLocStart(), "(")
3307       << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getLocEnd()), ")");
3308   S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3309       << FixItHint::CreateRemoval(Paren.Loc)
3310       << FixItHint::CreateRemoval(Paren.EndLoc);
3311 }
3312 
3313 /// Helper for figuring out the default CC for a function declarator type.  If
3314 /// this is the outermost chunk, then we can determine the CC from the
3315 /// declarator context.  If not, then this could be either a member function
3316 /// type or normal function type.
3317 static CallingConv
3318 getCCForDeclaratorChunk(Sema &S, Declarator &D,
3319                         const DeclaratorChunk::FunctionTypeInfo &FTI,
3320                         unsigned ChunkIndex) {
3321   assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3322 
3323   // Check for an explicit CC attribute.
3324   for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) {
3325     switch (Attr->getKind()) {
3326     CALLING_CONV_ATTRS_CASELIST: {
3327       // Ignore attributes that don't validate or can't apply to the
3328       // function type.  We'll diagnose the failure to apply them in
3329       // handleFunctionTypeAttr.
3330       CallingConv CC;
3331       if (!S.CheckCallingConvAttr(*Attr, CC) &&
3332           (!FTI.isVariadic || supportsVariadicCall(CC))) {
3333         return CC;
3334       }
3335       break;
3336     }
3337 
3338     default:
3339       break;
3340     }
3341   }
3342 
3343   bool IsCXXInstanceMethod = false;
3344 
3345   if (S.getLangOpts().CPlusPlus) {
3346     // Look inwards through parentheses to see if this chunk will form a
3347     // member pointer type or if we're the declarator.  Any type attributes
3348     // between here and there will override the CC we choose here.
3349     unsigned I = ChunkIndex;
3350     bool FoundNonParen = false;
3351     while (I && !FoundNonParen) {
3352       --I;
3353       if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3354         FoundNonParen = true;
3355     }
3356 
3357     if (FoundNonParen) {
3358       // If we're not the declarator, we're a regular function type unless we're
3359       // in a member pointer.
3360       IsCXXInstanceMethod =
3361           D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3362     } else if (D.getContext() == DeclaratorContext::LambdaExprContext) {
3363       // This can only be a call operator for a lambda, which is an instance
3364       // method.
3365       IsCXXInstanceMethod = true;
3366     } else {
3367       // We're the innermost decl chunk, so must be a function declarator.
3368       assert(D.isFunctionDeclarator());
3369 
3370       // If we're inside a record, we're declaring a method, but it could be
3371       // explicitly or implicitly static.
3372       IsCXXInstanceMethod =
3373           D.isFirstDeclarationOfMember() &&
3374           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3375           !D.isStaticMember();
3376     }
3377   }
3378 
3379   CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3380                                                          IsCXXInstanceMethod);
3381 
3382   // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3383   // and AMDGPU targets, hence it cannot be treated as a calling
3384   // convention attribute. This is the simplest place to infer
3385   // calling convention for OpenCL kernels.
3386   if (S.getLangOpts().OpenCL) {
3387     for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
3388          Attr; Attr = Attr->getNext()) {
3389       if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
3390         CC = CC_OpenCLKernel;
3391         break;
3392       }
3393     }
3394   }
3395 
3396   return CC;
3397 }
3398 
3399 namespace {
3400   /// A simple notion of pointer kinds, which matches up with the various
3401   /// pointer declarators.
3402   enum class SimplePointerKind {
3403     Pointer,
3404     BlockPointer,
3405     MemberPointer,
3406     Array,
3407   };
3408 } // end anonymous namespace
3409 
3410 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3411   switch (nullability) {
3412   case NullabilityKind::NonNull:
3413     if (!Ident__Nonnull)
3414       Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3415     return Ident__Nonnull;
3416 
3417   case NullabilityKind::Nullable:
3418     if (!Ident__Nullable)
3419       Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3420     return Ident__Nullable;
3421 
3422   case NullabilityKind::Unspecified:
3423     if (!Ident__Null_unspecified)
3424       Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3425     return Ident__Null_unspecified;
3426   }
3427   llvm_unreachable("Unknown nullability kind.");
3428 }
3429 
3430 /// Retrieve the identifier "NSError".
3431 IdentifierInfo *Sema::getNSErrorIdent() {
3432   if (!Ident_NSError)
3433     Ident_NSError = PP.getIdentifierInfo("NSError");
3434 
3435   return Ident_NSError;
3436 }
3437 
3438 /// Check whether there is a nullability attribute of any kind in the given
3439 /// attribute list.
3440 static bool hasNullabilityAttr(const AttributeList *attrs) {
3441   for (const AttributeList *attr = attrs; attr;
3442        attr = attr->getNext()) {
3443     if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3444         attr->getKind() == AttributeList::AT_TypeNullable ||
3445         attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3446       return true;
3447   }
3448 
3449   return false;
3450 }
3451 
3452 namespace {
3453   /// Describes the kind of a pointer a declarator describes.
3454   enum class PointerDeclaratorKind {
3455     // Not a pointer.
3456     NonPointer,
3457     // Single-level pointer.
3458     SingleLevelPointer,
3459     // Multi-level pointer (of any pointer kind).
3460     MultiLevelPointer,
3461     // CFFooRef*
3462     MaybePointerToCFRef,
3463     // CFErrorRef*
3464     CFErrorRefPointer,
3465     // NSError**
3466     NSErrorPointerPointer,
3467   };
3468 
3469   /// Describes a declarator chunk wrapping a pointer that marks inference as
3470   /// unexpected.
3471   // These values must be kept in sync with diagnostics.
3472   enum class PointerWrappingDeclaratorKind {
3473     /// Pointer is top-level.
3474     None = -1,
3475     /// Pointer is an array element.
3476     Array = 0,
3477     /// Pointer is the referent type of a C++ reference.
3478     Reference = 1
3479   };
3480 } // end anonymous namespace
3481 
3482 /// Classify the given declarator, whose type-specified is \c type, based on
3483 /// what kind of pointer it refers to.
3484 ///
3485 /// This is used to determine the default nullability.
3486 static PointerDeclaratorKind
3487 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3488                           PointerWrappingDeclaratorKind &wrappingKind) {
3489   unsigned numNormalPointers = 0;
3490 
3491   // For any dependent type, we consider it a non-pointer.
3492   if (type->isDependentType())
3493     return PointerDeclaratorKind::NonPointer;
3494 
3495   // Look through the declarator chunks to identify pointers.
3496   for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3497     DeclaratorChunk &chunk = declarator.getTypeObject(i);
3498     switch (chunk.Kind) {
3499     case DeclaratorChunk::Array:
3500       if (numNormalPointers == 0)
3501         wrappingKind = PointerWrappingDeclaratorKind::Array;
3502       break;
3503 
3504     case DeclaratorChunk::Function:
3505     case DeclaratorChunk::Pipe:
3506       break;
3507 
3508     case DeclaratorChunk::BlockPointer:
3509     case DeclaratorChunk::MemberPointer:
3510       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3511                                    : PointerDeclaratorKind::SingleLevelPointer;
3512 
3513     case DeclaratorChunk::Paren:
3514       break;
3515 
3516     case DeclaratorChunk::Reference:
3517       if (numNormalPointers == 0)
3518         wrappingKind = PointerWrappingDeclaratorKind::Reference;
3519       break;
3520 
3521     case DeclaratorChunk::Pointer:
3522       ++numNormalPointers;
3523       if (numNormalPointers > 2)
3524         return PointerDeclaratorKind::MultiLevelPointer;
3525       break;
3526     }
3527   }
3528 
3529   // Then, dig into the type specifier itself.
3530   unsigned numTypeSpecifierPointers = 0;
3531   do {
3532     // Decompose normal pointers.
3533     if (auto ptrType = type->getAs<PointerType>()) {
3534       ++numNormalPointers;
3535 
3536       if (numNormalPointers > 2)
3537         return PointerDeclaratorKind::MultiLevelPointer;
3538 
3539       type = ptrType->getPointeeType();
3540       ++numTypeSpecifierPointers;
3541       continue;
3542     }
3543 
3544     // Decompose block pointers.
3545     if (type->getAs<BlockPointerType>()) {
3546       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3547                                    : PointerDeclaratorKind::SingleLevelPointer;
3548     }
3549 
3550     // Decompose member pointers.
3551     if (type->getAs<MemberPointerType>()) {
3552       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3553                                    : PointerDeclaratorKind::SingleLevelPointer;
3554     }
3555 
3556     // Look at Objective-C object pointers.
3557     if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3558       ++numNormalPointers;
3559       ++numTypeSpecifierPointers;
3560 
3561       // If this is NSError**, report that.
3562       if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3563         if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3564             numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3565           return PointerDeclaratorKind::NSErrorPointerPointer;
3566         }
3567       }
3568 
3569       break;
3570     }
3571 
3572     // Look at Objective-C class types.
3573     if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3574       if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3575         if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3576           return PointerDeclaratorKind::NSErrorPointerPointer;
3577       }
3578 
3579       break;
3580     }
3581 
3582     // If at this point we haven't seen a pointer, we won't see one.
3583     if (numNormalPointers == 0)
3584       return PointerDeclaratorKind::NonPointer;
3585 
3586     if (auto recordType = type->getAs<RecordType>()) {
3587       RecordDecl *recordDecl = recordType->getDecl();
3588 
3589       bool isCFError = false;
3590       if (S.CFError) {
3591         // If we already know about CFError, test it directly.
3592         isCFError = (S.CFError == recordDecl);
3593       } else {
3594         // Check whether this is CFError, which we identify based on its bridge
3595         // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
3596         // now declared with "objc_bridge_mutable", so look for either one of
3597         // the two attributes.
3598         if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3599           IdentifierInfo *bridgedType = nullptr;
3600           if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
3601             bridgedType = bridgeAttr->getBridgedType();
3602           else if (auto bridgeAttr =
3603                        recordDecl->getAttr<ObjCBridgeMutableAttr>())
3604             bridgedType = bridgeAttr->getBridgedType();
3605 
3606           if (bridgedType == S.getNSErrorIdent()) {
3607             S.CFError = recordDecl;
3608             isCFError = true;
3609           }
3610         }
3611       }
3612 
3613       // If this is CFErrorRef*, report it as such.
3614       if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3615         return PointerDeclaratorKind::CFErrorRefPointer;
3616       }
3617       break;
3618     }
3619 
3620     break;
3621   } while (true);
3622 
3623   switch (numNormalPointers) {
3624   case 0:
3625     return PointerDeclaratorKind::NonPointer;
3626 
3627   case 1:
3628     return PointerDeclaratorKind::SingleLevelPointer;
3629 
3630   case 2:
3631     return PointerDeclaratorKind::MaybePointerToCFRef;
3632 
3633   default:
3634     return PointerDeclaratorKind::MultiLevelPointer;
3635   }
3636 }
3637 
3638 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3639                                                     SourceLocation loc) {
3640   // If we're anywhere in a function, method, or closure context, don't perform
3641   // completeness checks.
3642   for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3643     if (ctx->isFunctionOrMethod())
3644       return FileID();
3645 
3646     if (ctx->isFileContext())
3647       break;
3648   }
3649 
3650   // We only care about the expansion location.
3651   loc = S.SourceMgr.getExpansionLoc(loc);
3652   FileID file = S.SourceMgr.getFileID(loc);
3653   if (file.isInvalid())
3654     return FileID();
3655 
3656   // Retrieve file information.
3657   bool invalid = false;
3658   const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3659   if (invalid || !sloc.isFile())
3660     return FileID();
3661 
3662   // We don't want to perform completeness checks on the main file or in
3663   // system headers.
3664   const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3665   if (fileInfo.getIncludeLoc().isInvalid())
3666     return FileID();
3667   if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3668       S.Diags.getSuppressSystemWarnings()) {
3669     return FileID();
3670   }
3671 
3672   return file;
3673 }
3674 
3675 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3676 /// taking into account whitespace before and after.
3677 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
3678                              SourceLocation PointerLoc,
3679                              NullabilityKind Nullability) {
3680   assert(PointerLoc.isValid());
3681   if (PointerLoc.isMacroID())
3682     return;
3683 
3684   SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3685   if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3686     return;
3687 
3688   const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3689   if (!NextChar)
3690     return;
3691 
3692   SmallString<32> InsertionTextBuf{" "};
3693   InsertionTextBuf += getNullabilitySpelling(Nullability);
3694   InsertionTextBuf += " ";
3695   StringRef InsertionText = InsertionTextBuf.str();
3696 
3697   if (isWhitespace(*NextChar)) {
3698     InsertionText = InsertionText.drop_back();
3699   } else if (NextChar[-1] == '[') {
3700     if (NextChar[0] == ']')
3701       InsertionText = InsertionText.drop_back().drop_front();
3702     else
3703       InsertionText = InsertionText.drop_front();
3704   } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3705              !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3706     InsertionText = InsertionText.drop_back().drop_front();
3707   }
3708 
3709   Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3710 }
3711 
3712 static void emitNullabilityConsistencyWarning(Sema &S,
3713                                               SimplePointerKind PointerKind,
3714                                               SourceLocation PointerLoc,
3715                                               SourceLocation PointerEndLoc) {
3716   assert(PointerLoc.isValid());
3717 
3718   if (PointerKind == SimplePointerKind::Array) {
3719     S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3720   } else {
3721     S.Diag(PointerLoc, diag::warn_nullability_missing)
3722       << static_cast<unsigned>(PointerKind);
3723   }
3724 
3725   auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
3726   if (FixItLoc.isMacroID())
3727     return;
3728 
3729   auto addFixIt = [&](NullabilityKind Nullability) {
3730     auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
3731     Diag << static_cast<unsigned>(Nullability);
3732     Diag << static_cast<unsigned>(PointerKind);
3733     fixItNullability(S, Diag, FixItLoc, Nullability);
3734   };
3735   addFixIt(NullabilityKind::Nullable);
3736   addFixIt(NullabilityKind::NonNull);
3737 }
3738 
3739 /// Complains about missing nullability if the file containing \p pointerLoc
3740 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3741 /// pragma).
3742 ///
3743 /// If the file has \e not seen other uses of nullability, this particular
3744 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3745 static void
3746 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
3747                             SourceLocation pointerLoc,
3748                             SourceLocation pointerEndLoc = SourceLocation()) {
3749   // Determine which file we're performing consistency checking for.
3750   FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3751   if (file.isInvalid())
3752     return;
3753 
3754   // If we haven't seen any type nullability in this file, we won't warn now
3755   // about anything.
3756   FileNullability &fileNullability = S.NullabilityMap[file];
3757   if (!fileNullability.SawTypeNullability) {
3758     // If this is the first pointer declarator in the file, and the appropriate
3759     // warning is on, record it in case we need to diagnose it retroactively.
3760     diag::kind diagKind;
3761     if (pointerKind == SimplePointerKind::Array)
3762       diagKind = diag::warn_nullability_missing_array;
3763     else
3764       diagKind = diag::warn_nullability_missing;
3765 
3766     if (fileNullability.PointerLoc.isInvalid() &&
3767         !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3768       fileNullability.PointerLoc = pointerLoc;
3769       fileNullability.PointerEndLoc = pointerEndLoc;
3770       fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3771     }
3772 
3773     return;
3774   }
3775 
3776   // Complain about missing nullability.
3777   emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
3778 }
3779 
3780 /// Marks that a nullability feature has been used in the file containing
3781 /// \p loc.
3782 ///
3783 /// If this file already had pointer types in it that were missing nullability,
3784 /// the first such instance is retroactively diagnosed.
3785 ///
3786 /// \sa checkNullabilityConsistency
3787 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
3788   FileID file = getNullabilityCompletenessCheckFileID(S, loc);
3789   if (file.isInvalid())
3790     return;
3791 
3792   FileNullability &fileNullability = S.NullabilityMap[file];
3793   if (fileNullability.SawTypeNullability)
3794     return;
3795   fileNullability.SawTypeNullability = true;
3796 
3797   // If we haven't seen any type nullability before, now we have. Retroactively
3798   // diagnose the first unannotated pointer, if there was one.
3799   if (fileNullability.PointerLoc.isInvalid())
3800     return;
3801 
3802   auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3803   emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
3804                                     fileNullability.PointerEndLoc);
3805 }
3806 
3807 /// Returns true if any of the declarator chunks before \p endIndex include a
3808 /// level of indirection: array, pointer, reference, or pointer-to-member.
3809 ///
3810 /// Because declarator chunks are stored in outer-to-inner order, testing
3811 /// every chunk before \p endIndex is testing all chunks that embed the current
3812 /// chunk as part of their type.
3813 ///
3814 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3815 /// end index, in which case all chunks are tested.
3816 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3817   unsigned i = endIndex;
3818   while (i != 0) {
3819     // Walk outwards along the declarator chunks.
3820     --i;
3821     const DeclaratorChunk &DC = D.getTypeObject(i);
3822     switch (DC.Kind) {
3823     case DeclaratorChunk::Paren:
3824       break;
3825     case DeclaratorChunk::Array:
3826     case DeclaratorChunk::Pointer:
3827     case DeclaratorChunk::Reference:
3828     case DeclaratorChunk::MemberPointer:
3829       return true;
3830     case DeclaratorChunk::Function:
3831     case DeclaratorChunk::BlockPointer:
3832     case DeclaratorChunk::Pipe:
3833       // These are invalid anyway, so just ignore.
3834       break;
3835     }
3836   }
3837   return false;
3838 }
3839 
3840 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3841                                                 QualType declSpecType,
3842                                                 TypeSourceInfo *TInfo) {
3843   // The TypeSourceInfo that this function returns will not be a null type.
3844   // If there is an error, this function will fill in a dummy type as fallback.
3845   QualType T = declSpecType;
3846   Declarator &D = state.getDeclarator();
3847   Sema &S = state.getSema();
3848   ASTContext &Context = S.Context;
3849   const LangOptions &LangOpts = S.getLangOpts();
3850 
3851   // The name we're declaring, if any.
3852   DeclarationName Name;
3853   if (D.getIdentifier())
3854     Name = D.getIdentifier();
3855 
3856   // Does this declaration declare a typedef-name?
3857   bool IsTypedefName =
3858     D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3859     D.getContext() == DeclaratorContext::AliasDeclContext ||
3860     D.getContext() == DeclaratorContext::AliasTemplateContext;
3861 
3862   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3863   bool IsQualifiedFunction = T->isFunctionProtoType() &&
3864       (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3865        T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3866 
3867   // If T is 'decltype(auto)', the only declarators we can have are parens
3868   // and at most one function declarator if this is a function declaration.
3869   // If T is a deduced class template specialization type, we can have no
3870   // declarator chunks at all.
3871   if (auto *DT = T->getAs<DeducedType>()) {
3872     const AutoType *AT = T->getAs<AutoType>();
3873     bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
3874     if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
3875       for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3876         unsigned Index = E - I - 1;
3877         DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3878         unsigned DiagId = IsClassTemplateDeduction
3879                               ? diag::err_deduced_class_template_compound_type
3880                               : diag::err_decltype_auto_compound_type;
3881         unsigned DiagKind = 0;
3882         switch (DeclChunk.Kind) {
3883         case DeclaratorChunk::Paren:
3884           // FIXME: Rejecting this is a little silly.
3885           if (IsClassTemplateDeduction) {
3886             DiagKind = 4;
3887             break;
3888           }
3889           continue;
3890         case DeclaratorChunk::Function: {
3891           if (IsClassTemplateDeduction) {
3892             DiagKind = 3;
3893             break;
3894           }
3895           unsigned FnIndex;
3896           if (D.isFunctionDeclarationContext() &&
3897               D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3898             continue;
3899           DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3900           break;
3901         }
3902         case DeclaratorChunk::Pointer:
3903         case DeclaratorChunk::BlockPointer:
3904         case DeclaratorChunk::MemberPointer:
3905           DiagKind = 0;
3906           break;
3907         case DeclaratorChunk::Reference:
3908           DiagKind = 1;
3909           break;
3910         case DeclaratorChunk::Array:
3911           DiagKind = 2;
3912           break;
3913         case DeclaratorChunk::Pipe:
3914           break;
3915         }
3916 
3917         S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3918         D.setInvalidType(true);
3919         break;
3920       }
3921     }
3922   }
3923 
3924   // Determine whether we should infer _Nonnull on pointer types.
3925   Optional<NullabilityKind> inferNullability;
3926   bool inferNullabilityCS = false;
3927   bool inferNullabilityInnerOnly = false;
3928   bool inferNullabilityInnerOnlyComplete = false;
3929 
3930   // Are we in an assume-nonnull region?
3931   bool inAssumeNonNullRegion = false;
3932   SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
3933   if (assumeNonNullLoc.isValid()) {
3934     inAssumeNonNullRegion = true;
3935     recordNullabilitySeen(S, assumeNonNullLoc);
3936   }
3937 
3938   // Whether to complain about missing nullability specifiers or not.
3939   enum {
3940     /// Never complain.
3941     CAMN_No,
3942     /// Complain on the inner pointers (but not the outermost
3943     /// pointer).
3944     CAMN_InnerPointers,
3945     /// Complain about any pointers that don't have nullability
3946     /// specified or inferred.
3947     CAMN_Yes
3948   } complainAboutMissingNullability = CAMN_No;
3949   unsigned NumPointersRemaining = 0;
3950   auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
3951 
3952   if (IsTypedefName) {
3953     // For typedefs, we do not infer any nullability (the default),
3954     // and we only complain about missing nullability specifiers on
3955     // inner pointers.
3956     complainAboutMissingNullability = CAMN_InnerPointers;
3957 
3958     if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
3959         !T->getNullability(S.Context)) {
3960       // Note that we allow but don't require nullability on dependent types.
3961       ++NumPointersRemaining;
3962     }
3963 
3964     for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3965       DeclaratorChunk &chunk = D.getTypeObject(i);
3966       switch (chunk.Kind) {
3967       case DeclaratorChunk::Array:
3968       case DeclaratorChunk::Function:
3969       case DeclaratorChunk::Pipe:
3970         break;
3971 
3972       case DeclaratorChunk::BlockPointer:
3973       case DeclaratorChunk::MemberPointer:
3974         ++NumPointersRemaining;
3975         break;
3976 
3977       case DeclaratorChunk::Paren:
3978       case DeclaratorChunk::Reference:
3979         continue;
3980 
3981       case DeclaratorChunk::Pointer:
3982         ++NumPointersRemaining;
3983         continue;
3984       }
3985     }
3986   } else {
3987     bool isFunctionOrMethod = false;
3988     switch (auto context = state.getDeclarator().getContext()) {
3989     case DeclaratorContext::ObjCParameterContext:
3990     case DeclaratorContext::ObjCResultContext:
3991     case DeclaratorContext::PrototypeContext:
3992     case DeclaratorContext::TrailingReturnContext:
3993     case DeclaratorContext::TrailingReturnVarContext:
3994       isFunctionOrMethod = true;
3995       LLVM_FALLTHROUGH;
3996 
3997     case DeclaratorContext::MemberContext:
3998       if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3999         complainAboutMissingNullability = CAMN_No;
4000         break;
4001       }
4002 
4003       // Weak properties are inferred to be nullable.
4004       if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4005         inferNullability = NullabilityKind::Nullable;
4006         break;
4007       }
4008 
4009       LLVM_FALLTHROUGH;
4010 
4011     case DeclaratorContext::FileContext:
4012     case DeclaratorContext::KNRTypeListContext: {
4013       complainAboutMissingNullability = CAMN_Yes;
4014 
4015       // Nullability inference depends on the type and declarator.
4016       auto wrappingKind = PointerWrappingDeclaratorKind::None;
4017       switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4018       case PointerDeclaratorKind::NonPointer:
4019       case PointerDeclaratorKind::MultiLevelPointer:
4020         // Cannot infer nullability.
4021         break;
4022 
4023       case PointerDeclaratorKind::SingleLevelPointer:
4024         // Infer _Nonnull if we are in an assumes-nonnull region.
4025         if (inAssumeNonNullRegion) {
4026           complainAboutInferringWithinChunk = wrappingKind;
4027           inferNullability = NullabilityKind::NonNull;
4028           inferNullabilityCS =
4029               (context == DeclaratorContext::ObjCParameterContext ||
4030                context == DeclaratorContext::ObjCResultContext);
4031         }
4032         break;
4033 
4034       case PointerDeclaratorKind::CFErrorRefPointer:
4035       case PointerDeclaratorKind::NSErrorPointerPointer:
4036         // Within a function or method signature, infer _Nullable at both
4037         // levels.
4038         if (isFunctionOrMethod && inAssumeNonNullRegion)
4039           inferNullability = NullabilityKind::Nullable;
4040         break;
4041 
4042       case PointerDeclaratorKind::MaybePointerToCFRef:
4043         if (isFunctionOrMethod) {
4044           // On pointer-to-pointer parameters marked cf_returns_retained or
4045           // cf_returns_not_retained, if the outer pointer is explicit then
4046           // infer the inner pointer as _Nullable.
4047           auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
4048             while (NextAttr) {
4049               if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
4050                   NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
4051                 return true;
4052               NextAttr = NextAttr->getNext();
4053             }
4054             return false;
4055           };
4056           if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4057             if (hasCFReturnsAttr(D.getAttributes()) ||
4058                 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4059                 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
4060               inferNullability = NullabilityKind::Nullable;
4061               inferNullabilityInnerOnly = true;
4062             }
4063           }
4064         }
4065         break;
4066       }
4067       break;
4068     }
4069 
4070     case DeclaratorContext::ConversionIdContext:
4071       complainAboutMissingNullability = CAMN_Yes;
4072       break;
4073 
4074     case DeclaratorContext::AliasDeclContext:
4075     case DeclaratorContext::AliasTemplateContext:
4076     case DeclaratorContext::BlockContext:
4077     case DeclaratorContext::BlockLiteralContext:
4078     case DeclaratorContext::ConditionContext:
4079     case DeclaratorContext::CXXCatchContext:
4080     case DeclaratorContext::CXXNewContext:
4081     case DeclaratorContext::ForContext:
4082     case DeclaratorContext::InitStmtContext:
4083     case DeclaratorContext::LambdaExprContext:
4084     case DeclaratorContext::LambdaExprParameterContext:
4085     case DeclaratorContext::ObjCCatchContext:
4086     case DeclaratorContext::TemplateParamContext:
4087     case DeclaratorContext::TemplateArgContext:
4088     case DeclaratorContext::TemplateTypeArgContext:
4089     case DeclaratorContext::TypeNameContext:
4090     case DeclaratorContext::FunctionalCastContext:
4091       // Don't infer in these contexts.
4092       break;
4093     }
4094   }
4095 
4096   // Local function that returns true if its argument looks like a va_list.
4097   auto isVaList = [&S](QualType T) -> bool {
4098     auto *typedefTy = T->getAs<TypedefType>();
4099     if (!typedefTy)
4100       return false;
4101     TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4102     do {
4103       if (typedefTy->getDecl() == vaListTypedef)
4104         return true;
4105       if (auto *name = typedefTy->getDecl()->getIdentifier())
4106         if (name->isStr("va_list"))
4107           return true;
4108       typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4109     } while (typedefTy);
4110     return false;
4111   };
4112 
4113   // Local function that checks the nullability for a given pointer declarator.
4114   // Returns true if _Nonnull was inferred.
4115   auto inferPointerNullability = [&](SimplePointerKind pointerKind,
4116                                      SourceLocation pointerLoc,
4117                                      SourceLocation pointerEndLoc,
4118                                      AttributeList *&attrs) -> AttributeList * {
4119     // We've seen a pointer.
4120     if (NumPointersRemaining > 0)
4121       --NumPointersRemaining;
4122 
4123     // If a nullability attribute is present, there's nothing to do.
4124     if (hasNullabilityAttr(attrs))
4125       return nullptr;
4126 
4127     // If we're supposed to infer nullability, do so now.
4128     if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4129       AttributeList::Syntax syntax
4130         = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
4131                              : AttributeList::AS_Keyword;
4132       AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
4133                                          .create(
4134                                            S.getNullabilityKeyword(
4135                                              *inferNullability),
4136                                            SourceRange(pointerLoc),
4137                                            nullptr, SourceLocation(),
4138                                            nullptr, 0, syntax);
4139 
4140       spliceAttrIntoList(*nullabilityAttr, attrs);
4141 
4142       if (inferNullabilityCS) {
4143         state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4144           ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4145       }
4146 
4147       if (pointerLoc.isValid() &&
4148           complainAboutInferringWithinChunk !=
4149             PointerWrappingDeclaratorKind::None) {
4150         auto Diag =
4151             S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4152         Diag << static_cast<int>(complainAboutInferringWithinChunk);
4153         fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4154       }
4155 
4156       if (inferNullabilityInnerOnly)
4157         inferNullabilityInnerOnlyComplete = true;
4158       return nullabilityAttr;
4159     }
4160 
4161     // If we're supposed to complain about missing nullability, do so
4162     // now if it's truly missing.
4163     switch (complainAboutMissingNullability) {
4164     case CAMN_No:
4165       break;
4166 
4167     case CAMN_InnerPointers:
4168       if (NumPointersRemaining == 0)
4169         break;
4170       LLVM_FALLTHROUGH;
4171 
4172     case CAMN_Yes:
4173       checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4174     }
4175     return nullptr;
4176   };
4177 
4178   // If the type itself could have nullability but does not, infer pointer
4179   // nullability and perform consistency checking.
4180   if (S.CodeSynthesisContexts.empty()) {
4181     if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4182         !T->getNullability(S.Context)) {
4183       if (isVaList(T)) {
4184         // Record that we've seen a pointer, but do nothing else.
4185         if (NumPointersRemaining > 0)
4186           --NumPointersRemaining;
4187       } else {
4188         SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4189         if (T->isBlockPointerType())
4190           pointerKind = SimplePointerKind::BlockPointer;
4191         else if (T->isMemberPointerType())
4192           pointerKind = SimplePointerKind::MemberPointer;
4193 
4194         if (auto *attr = inferPointerNullability(
4195               pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4196               D.getDeclSpec().getLocEnd(),
4197               D.getMutableDeclSpec().getAttributes().getListRef())) {
4198           T = Context.getAttributedType(
4199                 AttributedType::getNullabilityAttrKind(*inferNullability),T,T);
4200           attr->setUsedAsTypeAttr();
4201         }
4202       }
4203     }
4204 
4205     if (complainAboutMissingNullability == CAMN_Yes &&
4206         T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4207         D.isPrototypeContext() &&
4208         !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4209       checkNullabilityConsistency(S, SimplePointerKind::Array,
4210                                   D.getDeclSpec().getTypeSpecTypeLoc());
4211     }
4212   }
4213 
4214   // Walk the DeclTypeInfo, building the recursive type as we go.
4215   // DeclTypeInfos are ordered from the identifier out, which is
4216   // opposite of what we want :).
4217   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4218     unsigned chunkIndex = e - i - 1;
4219     state.setCurrentChunkIndex(chunkIndex);
4220     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4221     IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4222     switch (DeclType.Kind) {
4223     case DeclaratorChunk::Paren:
4224       if (i == 0)
4225         warnAboutRedundantParens(S, D, T);
4226       T = S.BuildParenType(T);
4227       break;
4228     case DeclaratorChunk::BlockPointer:
4229       // If blocks are disabled, emit an error.
4230       if (!LangOpts.Blocks)
4231         S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4232 
4233       // Handle pointer nullability.
4234       inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4235                               DeclType.EndLoc, DeclType.getAttrListRef());
4236 
4237       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4238       if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4239         // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4240         // qualified with const.
4241         if (LangOpts.OpenCL)
4242           DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4243         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4244       }
4245       break;
4246     case DeclaratorChunk::Pointer:
4247       // Verify that we're not building a pointer to pointer to function with
4248       // exception specification.
4249       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4250         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4251         D.setInvalidType(true);
4252         // Build the type anyway.
4253       }
4254 
4255       // Handle pointer nullability
4256       inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4257                               DeclType.EndLoc, DeclType.getAttrListRef());
4258 
4259       if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
4260         T = Context.getObjCObjectPointerType(T);
4261         if (DeclType.Ptr.TypeQuals)
4262           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4263         break;
4264       }
4265 
4266       // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4267       // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4268       // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4269       if (LangOpts.OpenCL) {
4270         if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4271             T->isBlockPointerType()) {
4272           S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4273           D.setInvalidType(true);
4274         }
4275       }
4276 
4277       T = S.BuildPointerType(T, DeclType.Loc, Name);
4278       if (DeclType.Ptr.TypeQuals)
4279         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4280       break;
4281     case DeclaratorChunk::Reference: {
4282       // Verify that we're not building a reference to pointer to function with
4283       // exception specification.
4284       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4285         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4286         D.setInvalidType(true);
4287         // Build the type anyway.
4288       }
4289       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4290 
4291       if (DeclType.Ref.HasRestrict)
4292         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4293       break;
4294     }
4295     case DeclaratorChunk::Array: {
4296       // Verify that we're not building an array of pointers to function with
4297       // exception specification.
4298       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4299         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4300         D.setInvalidType(true);
4301         // Build the type anyway.
4302       }
4303       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4304       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4305       ArrayType::ArraySizeModifier ASM;
4306       if (ATI.isStar)
4307         ASM = ArrayType::Star;
4308       else if (ATI.hasStatic)
4309         ASM = ArrayType::Static;
4310       else
4311         ASM = ArrayType::Normal;
4312       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4313         // FIXME: This check isn't quite right: it allows star in prototypes
4314         // for function definitions, and disallows some edge cases detailed
4315         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4316         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4317         ASM = ArrayType::Normal;
4318         D.setInvalidType(true);
4319       }
4320 
4321       // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4322       // shall appear only in a declaration of a function parameter with an
4323       // array type, ...
4324       if (ASM == ArrayType::Static || ATI.TypeQuals) {
4325         if (!(D.isPrototypeContext() ||
4326               D.getContext() == DeclaratorContext::KNRTypeListContext)) {
4327           S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4328               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4329           // Remove the 'static' and the type qualifiers.
4330           if (ASM == ArrayType::Static)
4331             ASM = ArrayType::Normal;
4332           ATI.TypeQuals = 0;
4333           D.setInvalidType(true);
4334         }
4335 
4336         // C99 6.7.5.2p1: ... and then only in the outermost array type
4337         // derivation.
4338         if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4339           S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4340             (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4341           if (ASM == ArrayType::Static)
4342             ASM = ArrayType::Normal;
4343           ATI.TypeQuals = 0;
4344           D.setInvalidType(true);
4345         }
4346       }
4347       const AutoType *AT = T->getContainedAutoType();
4348       // Allow arrays of auto if we are a generic lambda parameter.
4349       // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4350       if (AT &&
4351           D.getContext() != DeclaratorContext::LambdaExprParameterContext) {
4352         // We've already diagnosed this for decltype(auto).
4353         if (!AT->isDecltypeAuto())
4354           S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4355             << getPrintableNameForEntity(Name) << T;
4356         T = QualType();
4357         break;
4358       }
4359 
4360       // Array parameters can be marked nullable as well, although it's not
4361       // necessary if they're marked 'static'.
4362       if (complainAboutMissingNullability == CAMN_Yes &&
4363           !hasNullabilityAttr(DeclType.getAttrs()) &&
4364           ASM != ArrayType::Static &&
4365           D.isPrototypeContext() &&
4366           !hasOuterPointerLikeChunk(D, chunkIndex)) {
4367         checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4368       }
4369 
4370       T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4371                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4372       break;
4373     }
4374     case DeclaratorChunk::Function: {
4375       // If the function declarator has a prototype (i.e. it is not () and
4376       // does not have a K&R-style identifier list), then the arguments are part
4377       // of the type, otherwise the argument list is ().
4378       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4379       IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
4380 
4381       // Check for auto functions and trailing return type and adjust the
4382       // return type accordingly.
4383       if (!D.isInvalidType()) {
4384         // trailing-return-type is only required if we're declaring a function,
4385         // and not, for instance, a pointer to a function.
4386         if (D.getDeclSpec().hasAutoTypeSpec() &&
4387             !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
4388             !S.getLangOpts().CPlusPlus14) {
4389           S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4390                  D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4391                      ? diag::err_auto_missing_trailing_return
4392                      : diag::err_deduced_return_type);
4393           T = Context.IntTy;
4394           D.setInvalidType(true);
4395         } else if (FTI.hasTrailingReturnType()) {
4396           // T must be exactly 'auto' at this point. See CWG issue 681.
4397           if (isa<ParenType>(T)) {
4398             S.Diag(D.getLocStart(),
4399                  diag::err_trailing_return_in_parens)
4400               << T << D.getSourceRange();
4401             D.setInvalidType(true);
4402           } else if (D.getName().getKind() ==
4403                      UnqualifiedIdKind::IK_DeductionGuideName) {
4404             if (T != Context.DependentTy) {
4405               S.Diag(D.getDeclSpec().getLocStart(),
4406                      diag::err_deduction_guide_with_complex_decl)
4407                   << D.getSourceRange();
4408               D.setInvalidType(true);
4409             }
4410           } else if (D.getContext() != DeclaratorContext::LambdaExprContext &&
4411                      (T.hasQualifiers() || !isa<AutoType>(T) ||
4412                       cast<AutoType>(T)->getKeyword() !=
4413                           AutoTypeKeyword::Auto)) {
4414             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4415                    diag::err_trailing_return_without_auto)
4416                 << T << D.getDeclSpec().getSourceRange();
4417             D.setInvalidType(true);
4418           }
4419           T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4420           if (T.isNull()) {
4421             // An error occurred parsing the trailing return type.
4422             T = Context.IntTy;
4423             D.setInvalidType(true);
4424           }
4425         }
4426       }
4427 
4428       // C99 6.7.5.3p1: The return type may not be a function or array type.
4429       // For conversion functions, we'll diagnose this particular error later.
4430       if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4431           (D.getName().getKind() !=
4432            UnqualifiedIdKind::IK_ConversionFunctionId)) {
4433         unsigned diagID = diag::err_func_returning_array_function;
4434         // Last processing chunk in block context means this function chunk
4435         // represents the block.
4436         if (chunkIndex == 0 &&
4437             D.getContext() == DeclaratorContext::BlockLiteralContext)
4438           diagID = diag::err_block_returning_array_function;
4439         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4440         T = Context.IntTy;
4441         D.setInvalidType(true);
4442       }
4443 
4444       // Do not allow returning half FP value.
4445       // FIXME: This really should be in BuildFunctionType.
4446       if (T->isHalfType()) {
4447         if (S.getLangOpts().OpenCL) {
4448           if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4449             S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4450                 << T << 0 /*pointer hint*/;
4451             D.setInvalidType(true);
4452           }
4453         } else if (!S.getLangOpts().HalfArgsAndReturns) {
4454           S.Diag(D.getIdentifierLoc(),
4455             diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4456           D.setInvalidType(true);
4457         }
4458       }
4459 
4460       if (LangOpts.OpenCL) {
4461         // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4462         // function.
4463         if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4464             T->isPipeType()) {
4465           S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4466               << T << 1 /*hint off*/;
4467           D.setInvalidType(true);
4468         }
4469         // OpenCL doesn't support variadic functions and blocks
4470         // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4471         // We also allow here any toolchain reserved identifiers.
4472         if (FTI.isVariadic &&
4473             !(D.getIdentifier() &&
4474               ((D.getIdentifier()->getName() == "printf" &&
4475                 LangOpts.OpenCLVersion >= 120) ||
4476                D.getIdentifier()->getName().startswith("__")))) {
4477           S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4478           D.setInvalidType(true);
4479         }
4480       }
4481 
4482       // Methods cannot return interface types. All ObjC objects are
4483       // passed by reference.
4484       if (T->isObjCObjectType()) {
4485         SourceLocation DiagLoc, FixitLoc;
4486         if (TInfo) {
4487           DiagLoc = TInfo->getTypeLoc().getLocStart();
4488           FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4489         } else {
4490           DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4491           FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4492         }
4493         S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4494           << 0 << T
4495           << FixItHint::CreateInsertion(FixitLoc, "*");
4496 
4497         T = Context.getObjCObjectPointerType(T);
4498         if (TInfo) {
4499           TypeLocBuilder TLB;
4500           TLB.pushFullCopy(TInfo->getTypeLoc());
4501           ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4502           TLoc.setStarLoc(FixitLoc);
4503           TInfo = TLB.getTypeSourceInfo(Context, T);
4504         }
4505 
4506         D.setInvalidType(true);
4507       }
4508 
4509       // cv-qualifiers on return types are pointless except when the type is a
4510       // class type in C++.
4511       if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4512           !(S.getLangOpts().CPlusPlus &&
4513             (T->isDependentType() || T->isRecordType()))) {
4514         if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4515             D.getFunctionDefinitionKind() == FDK_Definition) {
4516           // [6.9.1/3] qualified void return is invalid on a C
4517           // function definition.  Apparently ok on declarations and
4518           // in C++ though (!)
4519           S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4520         } else
4521           diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4522       }
4523 
4524       // Objective-C ARC ownership qualifiers are ignored on the function
4525       // return type (by type canonicalization). Complain if this attribute
4526       // was written here.
4527       if (T.getQualifiers().hasObjCLifetime()) {
4528         SourceLocation AttrLoc;
4529         if (chunkIndex + 1 < D.getNumTypeObjects()) {
4530           DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4531           for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
4532                Attr; Attr = Attr->getNext()) {
4533             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4534               AttrLoc = Attr->getLoc();
4535               break;
4536             }
4537           }
4538         }
4539         if (AttrLoc.isInvalid()) {
4540           for (const AttributeList *Attr
4541                  = D.getDeclSpec().getAttributes().getList();
4542                Attr; Attr = Attr->getNext()) {
4543             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4544               AttrLoc = Attr->getLoc();
4545               break;
4546             }
4547           }
4548         }
4549 
4550         if (AttrLoc.isValid()) {
4551           // The ownership attributes are almost always written via
4552           // the predefined
4553           // __strong/__weak/__autoreleasing/__unsafe_unretained.
4554           if (AttrLoc.isMacroID())
4555             AttrLoc =
4556                 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
4557 
4558           S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4559             << T.getQualifiers().getObjCLifetime();
4560         }
4561       }
4562 
4563       if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4564         // C++ [dcl.fct]p6:
4565         //   Types shall not be defined in return or parameter types.
4566         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4567         S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4568           << Context.getTypeDeclType(Tag);
4569       }
4570 
4571       // Exception specs are not allowed in typedefs. Complain, but add it
4572       // anyway.
4573       if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
4574         S.Diag(FTI.getExceptionSpecLocBeg(),
4575                diag::err_exception_spec_in_typedef)
4576             << (D.getContext() == DeclaratorContext::AliasDeclContext ||
4577                 D.getContext() == DeclaratorContext::AliasTemplateContext);
4578 
4579       // If we see "T var();" or "T var(T());" at block scope, it is probably
4580       // an attempt to initialize a variable, not a function declaration.
4581       if (FTI.isAmbiguous)
4582         warnAboutAmbiguousFunction(S, D, DeclType, T);
4583 
4584       FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
4585 
4586       if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
4587                                             && !LangOpts.OpenCL) {
4588         // Simple void foo(), where the incoming T is the result type.
4589         T = Context.getFunctionNoProtoType(T, EI);
4590       } else {
4591         // We allow a zero-parameter variadic function in C if the
4592         // function is marked with the "overloadable" attribute. Scan
4593         // for this attribute now.
4594         if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
4595           bool Overloadable = false;
4596           for (const AttributeList *Attrs = D.getAttributes();
4597                Attrs; Attrs = Attrs->getNext()) {
4598             if (Attrs->getKind() == AttributeList::AT_Overloadable) {
4599               Overloadable = true;
4600               break;
4601             }
4602           }
4603 
4604           if (!Overloadable)
4605             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4606         }
4607 
4608         if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4609           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4610           // definition.
4611           S.Diag(FTI.Params[0].IdentLoc,
4612                  diag::err_ident_list_in_fn_declaration);
4613           D.setInvalidType(true);
4614           // Recover by creating a K&R-style function type.
4615           T = Context.getFunctionNoProtoType(T, EI);
4616           break;
4617         }
4618 
4619         FunctionProtoType::ExtProtoInfo EPI;
4620         EPI.ExtInfo = EI;
4621         EPI.Variadic = FTI.isVariadic;
4622         EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4623         EPI.TypeQuals = FTI.TypeQuals;
4624         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4625                     : FTI.RefQualifierIsLValueRef? RQ_LValue
4626                     : RQ_RValue;
4627 
4628         // Otherwise, we have a function with a parameter list that is
4629         // potentially variadic.
4630         SmallVector<QualType, 16> ParamTys;
4631         ParamTys.reserve(FTI.NumParams);
4632 
4633         SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4634           ExtParameterInfos(FTI.NumParams);
4635         bool HasAnyInterestingExtParameterInfos = false;
4636 
4637         for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4638           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4639           QualType ParamTy = Param->getType();
4640           assert(!ParamTy.isNull() && "Couldn't parse type?");
4641 
4642           // Look for 'void'.  void is allowed only as a single parameter to a
4643           // function with no other parameters (C99 6.7.5.3p10).  We record
4644           // int(void) as a FunctionProtoType with an empty parameter list.
4645           if (ParamTy->isVoidType()) {
4646             // If this is something like 'float(int, void)', reject it.  'void'
4647             // is an incomplete type (C99 6.2.5p19) and function decls cannot
4648             // have parameters of incomplete type.
4649             if (FTI.NumParams != 1 || FTI.isVariadic) {
4650               S.Diag(DeclType.Loc, diag::err_void_only_param);
4651               ParamTy = Context.IntTy;
4652               Param->setType(ParamTy);
4653             } else if (FTI.Params[i].Ident) {
4654               // Reject, but continue to parse 'int(void abc)'.
4655               S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4656               ParamTy = Context.IntTy;
4657               Param->setType(ParamTy);
4658             } else {
4659               // Reject, but continue to parse 'float(const void)'.
4660               if (ParamTy.hasQualifiers())
4661                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4662 
4663               // Do not add 'void' to the list.
4664               break;
4665             }
4666           } else if (ParamTy->isHalfType()) {
4667             // Disallow half FP parameters.
4668             // FIXME: This really should be in BuildFunctionType.
4669             if (S.getLangOpts().OpenCL) {
4670               if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4671                 S.Diag(Param->getLocation(),
4672                   diag::err_opencl_half_param) << ParamTy;
4673                 D.setInvalidType();
4674                 Param->setInvalidDecl();
4675               }
4676             } else if (!S.getLangOpts().HalfArgsAndReturns) {
4677               S.Diag(Param->getLocation(),
4678                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4679               D.setInvalidType();
4680             }
4681           } else if (!FTI.hasPrototype) {
4682             if (ParamTy->isPromotableIntegerType()) {
4683               ParamTy = Context.getPromotedIntegerType(ParamTy);
4684               Param->setKNRPromoted(true);
4685             } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4686               if (BTy->getKind() == BuiltinType::Float) {
4687                 ParamTy = Context.DoubleTy;
4688                 Param->setKNRPromoted(true);
4689               }
4690             }
4691           }
4692 
4693           if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4694             ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4695             HasAnyInterestingExtParameterInfos = true;
4696           }
4697 
4698           if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4699             ExtParameterInfos[i] =
4700               ExtParameterInfos[i].withABI(attr->getABI());
4701             HasAnyInterestingExtParameterInfos = true;
4702           }
4703 
4704           if (Param->hasAttr<PassObjectSizeAttr>()) {
4705             ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4706             HasAnyInterestingExtParameterInfos = true;
4707           }
4708 
4709           if (Param->hasAttr<NoEscapeAttr>()) {
4710             ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
4711             HasAnyInterestingExtParameterInfos = true;
4712           }
4713 
4714           ParamTys.push_back(ParamTy);
4715         }
4716 
4717         if (HasAnyInterestingExtParameterInfos) {
4718           EPI.ExtParameterInfos = ExtParameterInfos.data();
4719           checkExtParameterInfos(S, ParamTys, EPI,
4720               [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4721         }
4722 
4723         SmallVector<QualType, 4> Exceptions;
4724         SmallVector<ParsedType, 2> DynamicExceptions;
4725         SmallVector<SourceRange, 2> DynamicExceptionRanges;
4726         Expr *NoexceptExpr = nullptr;
4727 
4728         if (FTI.getExceptionSpecType() == EST_Dynamic) {
4729           // FIXME: It's rather inefficient to have to split into two vectors
4730           // here.
4731           unsigned N = FTI.getNumExceptions();
4732           DynamicExceptions.reserve(N);
4733           DynamicExceptionRanges.reserve(N);
4734           for (unsigned I = 0; I != N; ++I) {
4735             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4736             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4737           }
4738         } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
4739           NoexceptExpr = FTI.NoexceptExpr;
4740         }
4741 
4742         S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4743                                       FTI.getExceptionSpecType(),
4744                                       DynamicExceptions,
4745                                       DynamicExceptionRanges,
4746                                       NoexceptExpr,
4747                                       Exceptions,
4748                                       EPI.ExceptionSpec);
4749 
4750         T = Context.getFunctionType(T, ParamTys, EPI);
4751       }
4752       break;
4753     }
4754     case DeclaratorChunk::MemberPointer: {
4755       // The scope spec must refer to a class, or be dependent.
4756       CXXScopeSpec &SS = DeclType.Mem.Scope();
4757       QualType ClsType;
4758 
4759       // Handle pointer nullability.
4760       inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
4761                               DeclType.EndLoc, DeclType.getAttrListRef());
4762 
4763       if (SS.isInvalid()) {
4764         // Avoid emitting extra errors if we already errored on the scope.
4765         D.setInvalidType(true);
4766       } else if (S.isDependentScopeSpecifier(SS) ||
4767                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4768         NestedNameSpecifier *NNS = SS.getScopeRep();
4769         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4770         switch (NNS->getKind()) {
4771         case NestedNameSpecifier::Identifier:
4772           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4773                                                  NNS->getAsIdentifier());
4774           break;
4775 
4776         case NestedNameSpecifier::Namespace:
4777         case NestedNameSpecifier::NamespaceAlias:
4778         case NestedNameSpecifier::Global:
4779         case NestedNameSpecifier::Super:
4780           llvm_unreachable("Nested-name-specifier must name a type");
4781 
4782         case NestedNameSpecifier::TypeSpec:
4783         case NestedNameSpecifier::TypeSpecWithTemplate:
4784           ClsType = QualType(NNS->getAsType(), 0);
4785           // Note: if the NNS has a prefix and ClsType is a nondependent
4786           // TemplateSpecializationType, then the NNS prefix is NOT included
4787           // in ClsType; hence we wrap ClsType into an ElaboratedType.
4788           // NOTE: in particular, no wrap occurs if ClsType already is an
4789           // Elaborated, DependentName, or DependentTemplateSpecialization.
4790           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4791             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4792           break;
4793         }
4794       } else {
4795         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4796              diag::err_illegal_decl_mempointer_in_nonclass)
4797           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4798           << DeclType.Mem.Scope().getRange();
4799         D.setInvalidType(true);
4800       }
4801 
4802       if (!ClsType.isNull())
4803         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4804                                      D.getIdentifier());
4805       if (T.isNull()) {
4806         T = Context.IntTy;
4807         D.setInvalidType(true);
4808       } else if (DeclType.Mem.TypeQuals) {
4809         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4810       }
4811       break;
4812     }
4813 
4814     case DeclaratorChunk::Pipe: {
4815       T = S.BuildReadPipeType(T, DeclType.Loc);
4816       processTypeAttrs(state, T, TAL_DeclSpec,
4817                        D.getDeclSpec().getAttributes().getList());
4818       break;
4819     }
4820     }
4821 
4822     if (T.isNull()) {
4823       D.setInvalidType(true);
4824       T = Context.IntTy;
4825     }
4826 
4827     // See if there are any attributes on this declarator chunk.
4828     processTypeAttrs(state, T, TAL_DeclChunk,
4829                      const_cast<AttributeList *>(DeclType.getAttrs()));
4830   }
4831 
4832   // GNU warning -Wstrict-prototypes
4833   //   Warn if a function declaration is without a prototype.
4834   //   This warning is issued for all kinds of unprototyped function
4835   //   declarations (i.e. function type typedef, function pointer etc.)
4836   //   C99 6.7.5.3p14:
4837   //   The empty list in a function declarator that is not part of a definition
4838   //   of that function specifies that no information about the number or types
4839   //   of the parameters is supplied.
4840   if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
4841     bool IsBlock = false;
4842     for (const DeclaratorChunk &DeclType : D.type_objects()) {
4843       switch (DeclType.Kind) {
4844       case DeclaratorChunk::BlockPointer:
4845         IsBlock = true;
4846         break;
4847       case DeclaratorChunk::Function: {
4848         const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4849         if (FTI.NumParams == 0 && !FTI.isVariadic)
4850           S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4851               << IsBlock
4852               << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4853         IsBlock = false;
4854         break;
4855       }
4856       default:
4857         break;
4858       }
4859     }
4860   }
4861 
4862   assert(!T.isNull() && "T must not be null after this point");
4863 
4864   if (LangOpts.CPlusPlus && T->isFunctionType()) {
4865     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4866     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4867 
4868     // C++ 8.3.5p4:
4869     //   A cv-qualifier-seq shall only be part of the function type
4870     //   for a nonstatic member function, the function type to which a pointer
4871     //   to member refers, or the top-level function type of a function typedef
4872     //   declaration.
4873     //
4874     // Core issue 547 also allows cv-qualifiers on function types that are
4875     // top-level template type arguments.
4876     enum { NonMember, Member, DeductionGuide } Kind = NonMember;
4877     if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
4878       Kind = DeductionGuide;
4879     else if (!D.getCXXScopeSpec().isSet()) {
4880       if ((D.getContext() == DeclaratorContext::MemberContext ||
4881            D.getContext() == DeclaratorContext::LambdaExprContext) &&
4882           !D.getDeclSpec().isFriendSpecified())
4883         Kind = Member;
4884     } else {
4885       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4886       if (!DC || DC->isRecord())
4887         Kind = Member;
4888     }
4889 
4890     // C++11 [dcl.fct]p6 (w/DR1417):
4891     // An attempt to specify a function type with a cv-qualifier-seq or a
4892     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4893     //  - the function type for a non-static member function,
4894     //  - the function type to which a pointer to member refers,
4895     //  - the top-level function type of a function typedef declaration or
4896     //    alias-declaration,
4897     //  - the type-id in the default argument of a type-parameter, or
4898     //  - the type-id of a template-argument for a type-parameter
4899     //
4900     // FIXME: Checking this here is insufficient. We accept-invalid on:
4901     //
4902     //   template<typename T> struct S { void f(T); };
4903     //   S<int() const> s;
4904     //
4905     // ... for instance.
4906     if (IsQualifiedFunction &&
4907         !(Kind == Member &&
4908           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4909         !IsTypedefName &&
4910         D.getContext() != DeclaratorContext::TemplateArgContext &&
4911         D.getContext() != DeclaratorContext::TemplateTypeArgContext) {
4912       SourceLocation Loc = D.getLocStart();
4913       SourceRange RemovalRange;
4914       unsigned I;
4915       if (D.isFunctionDeclarator(I)) {
4916         SmallVector<SourceLocation, 4> RemovalLocs;
4917         const DeclaratorChunk &Chunk = D.getTypeObject(I);
4918         assert(Chunk.Kind == DeclaratorChunk::Function);
4919         if (Chunk.Fun.hasRefQualifier())
4920           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4921         if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4922           RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4923         if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4924           RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4925         if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4926           RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4927         if (!RemovalLocs.empty()) {
4928           llvm::sort(RemovalLocs.begin(), RemovalLocs.end(),
4929                      BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4930           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4931           Loc = RemovalLocs.front();
4932         }
4933       }
4934 
4935       S.Diag(Loc, diag::err_invalid_qualified_function_type)
4936         << Kind << D.isFunctionDeclarator() << T
4937         << getFunctionQualifiersAsString(FnTy)
4938         << FixItHint::CreateRemoval(RemovalRange);
4939 
4940       // Strip the cv-qualifiers and ref-qualifiers from the type.
4941       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4942       EPI.TypeQuals = 0;
4943       EPI.RefQualifier = RQ_None;
4944 
4945       T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4946                                   EPI);
4947       // Rebuild any parens around the identifier in the function type.
4948       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4949         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4950           break;
4951         T = S.BuildParenType(T);
4952       }
4953     }
4954   }
4955 
4956   // Apply any undistributed attributes from the declarator.
4957   processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4958 
4959   // Diagnose any ignored type attributes.
4960   state.diagnoseIgnoredTypeAttrs(T);
4961 
4962   // C++0x [dcl.constexpr]p9:
4963   //  A constexpr specifier used in an object declaration declares the object
4964   //  as const.
4965   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4966     T.addConst();
4967   }
4968 
4969   // If there was an ellipsis in the declarator, the declaration declares a
4970   // parameter pack whose type may be a pack expansion type.
4971   if (D.hasEllipsis()) {
4972     // C++0x [dcl.fct]p13:
4973     //   A declarator-id or abstract-declarator containing an ellipsis shall
4974     //   only be used in a parameter-declaration. Such a parameter-declaration
4975     //   is a parameter pack (14.5.3). [...]
4976     switch (D.getContext()) {
4977     case DeclaratorContext::PrototypeContext:
4978     case DeclaratorContext::LambdaExprParameterContext:
4979       // C++0x [dcl.fct]p13:
4980       //   [...] When it is part of a parameter-declaration-clause, the
4981       //   parameter pack is a function parameter pack (14.5.3). The type T
4982       //   of the declarator-id of the function parameter pack shall contain
4983       //   a template parameter pack; each template parameter pack in T is
4984       //   expanded by the function parameter pack.
4985       //
4986       // We represent function parameter packs as function parameters whose
4987       // type is a pack expansion.
4988       if (!T->containsUnexpandedParameterPack()) {
4989         S.Diag(D.getEllipsisLoc(),
4990              diag::err_function_parameter_pack_without_parameter_packs)
4991           << T <<  D.getSourceRange();
4992         D.setEllipsisLoc(SourceLocation());
4993       } else {
4994         T = Context.getPackExpansionType(T, None);
4995       }
4996       break;
4997     case DeclaratorContext::TemplateParamContext:
4998       // C++0x [temp.param]p15:
4999       //   If a template-parameter is a [...] is a parameter-declaration that
5000       //   declares a parameter pack (8.3.5), then the template-parameter is a
5001       //   template parameter pack (14.5.3).
5002       //
5003       // Note: core issue 778 clarifies that, if there are any unexpanded
5004       // parameter packs in the type of the non-type template parameter, then
5005       // it expands those parameter packs.
5006       if (T->containsUnexpandedParameterPack())
5007         T = Context.getPackExpansionType(T, None);
5008       else
5009         S.Diag(D.getEllipsisLoc(),
5010                LangOpts.CPlusPlus11
5011                  ? diag::warn_cxx98_compat_variadic_templates
5012                  : diag::ext_variadic_templates);
5013       break;
5014 
5015     case DeclaratorContext::FileContext:
5016     case DeclaratorContext::KNRTypeListContext:
5017     case DeclaratorContext::ObjCParameterContext:  // FIXME: special diagnostic
5018                                                    // here?
5019     case DeclaratorContext::ObjCResultContext:     // FIXME: special diagnostic
5020                                                    // here?
5021     case DeclaratorContext::TypeNameContext:
5022     case DeclaratorContext::FunctionalCastContext:
5023     case DeclaratorContext::CXXNewContext:
5024     case DeclaratorContext::AliasDeclContext:
5025     case DeclaratorContext::AliasTemplateContext:
5026     case DeclaratorContext::MemberContext:
5027     case DeclaratorContext::BlockContext:
5028     case DeclaratorContext::ForContext:
5029     case DeclaratorContext::InitStmtContext:
5030     case DeclaratorContext::ConditionContext:
5031     case DeclaratorContext::CXXCatchContext:
5032     case DeclaratorContext::ObjCCatchContext:
5033     case DeclaratorContext::BlockLiteralContext:
5034     case DeclaratorContext::LambdaExprContext:
5035     case DeclaratorContext::ConversionIdContext:
5036     case DeclaratorContext::TrailingReturnContext:
5037     case DeclaratorContext::TrailingReturnVarContext:
5038     case DeclaratorContext::TemplateArgContext:
5039     case DeclaratorContext::TemplateTypeArgContext:
5040       // FIXME: We may want to allow parameter packs in block-literal contexts
5041       // in the future.
5042       S.Diag(D.getEllipsisLoc(),
5043              diag::err_ellipsis_in_declarator_not_parameter);
5044       D.setEllipsisLoc(SourceLocation());
5045       break;
5046     }
5047   }
5048 
5049   assert(!T.isNull() && "T must not be null at the end of this function");
5050   if (D.isInvalidType())
5051     return Context.getTrivialTypeSourceInfo(T);
5052 
5053   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
5054 }
5055 
5056 /// GetTypeForDeclarator - Convert the type for the specified
5057 /// declarator to Type instances.
5058 ///
5059 /// The result of this call will never be null, but the associated
5060 /// type may be a null type if there's an unrecoverable error.
5061 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5062   // Determine the type of the declarator. Not all forms of declarator
5063   // have a type.
5064 
5065   TypeProcessingState state(*this, D);
5066 
5067   TypeSourceInfo *ReturnTypeInfo = nullptr;
5068   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5069   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5070     inferARCWriteback(state, T);
5071 
5072   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5073 }
5074 
5075 static void transferARCOwnershipToDeclSpec(Sema &S,
5076                                            QualType &declSpecTy,
5077                                            Qualifiers::ObjCLifetime ownership) {
5078   if (declSpecTy->isObjCRetainableType() &&
5079       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5080     Qualifiers qs;
5081     qs.addObjCLifetime(ownership);
5082     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5083   }
5084 }
5085 
5086 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5087                                             Qualifiers::ObjCLifetime ownership,
5088                                             unsigned chunkIndex) {
5089   Sema &S = state.getSema();
5090   Declarator &D = state.getDeclarator();
5091 
5092   // Look for an explicit lifetime attribute.
5093   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5094   for (const AttributeList *attr = chunk.getAttrs(); attr;
5095          attr = attr->getNext())
5096     if (attr->getKind() == AttributeList::AT_ObjCOwnership)
5097       return;
5098 
5099   const char *attrStr = nullptr;
5100   switch (ownership) {
5101   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5102   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5103   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5104   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5105   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5106   }
5107 
5108   IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5109   Arg->Ident = &S.Context.Idents.get(attrStr);
5110   Arg->Loc = SourceLocation();
5111 
5112   ArgsUnion Args(Arg);
5113 
5114   // If there wasn't one, add one (with an invalid source location
5115   // so that we don't make an AttributedType for it).
5116   AttributeList *attr = D.getAttributePool()
5117     .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
5118             /*scope*/ nullptr, SourceLocation(),
5119             /*args*/ &Args, 1, AttributeList::AS_GNU);
5120   spliceAttrIntoList(*attr, chunk.getAttrListRef());
5121 
5122   // TODO: mark whether we did this inference?
5123 }
5124 
5125 /// Used for transferring ownership in casts resulting in l-values.
5126 static void transferARCOwnership(TypeProcessingState &state,
5127                                  QualType &declSpecTy,
5128                                  Qualifiers::ObjCLifetime ownership) {
5129   Sema &S = state.getSema();
5130   Declarator &D = state.getDeclarator();
5131 
5132   int inner = -1;
5133   bool hasIndirection = false;
5134   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5135     DeclaratorChunk &chunk = D.getTypeObject(i);
5136     switch (chunk.Kind) {
5137     case DeclaratorChunk::Paren:
5138       // Ignore parens.
5139       break;
5140 
5141     case DeclaratorChunk::Array:
5142     case DeclaratorChunk::Reference:
5143     case DeclaratorChunk::Pointer:
5144       if (inner != -1)
5145         hasIndirection = true;
5146       inner = i;
5147       break;
5148 
5149     case DeclaratorChunk::BlockPointer:
5150       if (inner != -1)
5151         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5152       return;
5153 
5154     case DeclaratorChunk::Function:
5155     case DeclaratorChunk::MemberPointer:
5156     case DeclaratorChunk::Pipe:
5157       return;
5158     }
5159   }
5160 
5161   if (inner == -1)
5162     return;
5163 
5164   DeclaratorChunk &chunk = D.getTypeObject(inner);
5165   if (chunk.Kind == DeclaratorChunk::Pointer) {
5166     if (declSpecTy->isObjCRetainableType())
5167       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5168     if (declSpecTy->isObjCObjectType() && hasIndirection)
5169       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5170   } else {
5171     assert(chunk.Kind == DeclaratorChunk::Array ||
5172            chunk.Kind == DeclaratorChunk::Reference);
5173     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5174   }
5175 }
5176 
5177 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5178   TypeProcessingState state(*this, D);
5179 
5180   TypeSourceInfo *ReturnTypeInfo = nullptr;
5181   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5182 
5183   if (getLangOpts().ObjC1) {
5184     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5185     if (ownership != Qualifiers::OCL_None)
5186       transferARCOwnership(state, declSpecTy, ownership);
5187   }
5188 
5189   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5190 }
5191 
5192 /// Map an AttributedType::Kind to an AttributeList::Kind.
5193 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
5194   switch (kind) {
5195   case AttributedType::attr_address_space:
5196     return AttributeList::AT_AddressSpace;
5197   case AttributedType::attr_regparm:
5198     return AttributeList::AT_Regparm;
5199   case AttributedType::attr_vector_size:
5200     return AttributeList::AT_VectorSize;
5201   case AttributedType::attr_neon_vector_type:
5202     return AttributeList::AT_NeonVectorType;
5203   case AttributedType::attr_neon_polyvector_type:
5204     return AttributeList::AT_NeonPolyVectorType;
5205   case AttributedType::attr_objc_gc:
5206     return AttributeList::AT_ObjCGC;
5207   case AttributedType::attr_objc_ownership:
5208   case AttributedType::attr_objc_inert_unsafe_unretained:
5209     return AttributeList::AT_ObjCOwnership;
5210   case AttributedType::attr_noreturn:
5211     return AttributeList::AT_NoReturn;
5212   case AttributedType::attr_nocf_check:
5213     return AttributeList::AT_AnyX86NoCfCheck;
5214   case AttributedType::attr_cdecl:
5215     return AttributeList::AT_CDecl;
5216   case AttributedType::attr_fastcall:
5217     return AttributeList::AT_FastCall;
5218   case AttributedType::attr_stdcall:
5219     return AttributeList::AT_StdCall;
5220   case AttributedType::attr_thiscall:
5221     return AttributeList::AT_ThisCall;
5222   case AttributedType::attr_regcall:
5223     return AttributeList::AT_RegCall;
5224   case AttributedType::attr_pascal:
5225     return AttributeList::AT_Pascal;
5226   case AttributedType::attr_swiftcall:
5227     return AttributeList::AT_SwiftCall;
5228   case AttributedType::attr_vectorcall:
5229     return AttributeList::AT_VectorCall;
5230   case AttributedType::attr_pcs:
5231   case AttributedType::attr_pcs_vfp:
5232     return AttributeList::AT_Pcs;
5233   case AttributedType::attr_inteloclbicc:
5234     return AttributeList::AT_IntelOclBicc;
5235   case AttributedType::attr_ms_abi:
5236     return AttributeList::AT_MSABI;
5237   case AttributedType::attr_sysv_abi:
5238     return AttributeList::AT_SysVABI;
5239   case AttributedType::attr_preserve_most:
5240     return AttributeList::AT_PreserveMost;
5241   case AttributedType::attr_preserve_all:
5242     return AttributeList::AT_PreserveAll;
5243   case AttributedType::attr_ptr32:
5244     return AttributeList::AT_Ptr32;
5245   case AttributedType::attr_ptr64:
5246     return AttributeList::AT_Ptr64;
5247   case AttributedType::attr_sptr:
5248     return AttributeList::AT_SPtr;
5249   case AttributedType::attr_uptr:
5250     return AttributeList::AT_UPtr;
5251   case AttributedType::attr_nonnull:
5252     return AttributeList::AT_TypeNonNull;
5253   case AttributedType::attr_nullable:
5254     return AttributeList::AT_TypeNullable;
5255   case AttributedType::attr_null_unspecified:
5256     return AttributeList::AT_TypeNullUnspecified;
5257   case AttributedType::attr_objc_kindof:
5258     return AttributeList::AT_ObjCKindOf;
5259   case AttributedType::attr_ns_returns_retained:
5260     return AttributeList::AT_NSReturnsRetained;
5261   }
5262   llvm_unreachable("unexpected attribute kind!");
5263 }
5264 
5265 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5266                                   const AttributeList *attrs,
5267                                   const AttributeList *DeclAttrs = nullptr) {
5268   // DeclAttrs and attrs cannot be both empty.
5269   assert((attrs || DeclAttrs) &&
5270          "no type attributes in the expected location!");
5271 
5272   AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
5273   // Try to search for an attribute of matching kind in attrs list.
5274   while (attrs && attrs->getKind() != parsedKind)
5275     attrs = attrs->getNext();
5276   if (!attrs) {
5277     // No matching type attribute in attrs list found.
5278     // Try searching through C++11 attributes in the declarator attribute list.
5279     while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
5280                          DeclAttrs->getKind() != parsedKind))
5281       DeclAttrs = DeclAttrs->getNext();
5282     attrs = DeclAttrs;
5283   }
5284 
5285   assert(attrs && "no matching type attribute in expected location!");
5286 
5287   TL.setAttrNameLoc(attrs->getLoc());
5288   if (TL.hasAttrExprOperand()) {
5289     assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
5290     TL.setAttrExprOperand(attrs->getArgAsExpr(0));
5291   } else if (TL.hasAttrEnumOperand()) {
5292     assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
5293            "unexpected attribute operand kind");
5294     if (attrs->isArgIdent(0))
5295       TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
5296     else
5297       TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
5298   }
5299 
5300   // FIXME: preserve this information to here.
5301   if (TL.hasAttrOperand())
5302     TL.setAttrOperandParensRange(SourceRange());
5303 }
5304 
5305 namespace {
5306   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5307     ASTContext &Context;
5308     const DeclSpec &DS;
5309 
5310   public:
5311     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
5312       : Context(Context), DS(DS) {}
5313 
5314     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5315       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
5316       Visit(TL.getModifiedLoc());
5317     }
5318     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5319       Visit(TL.getUnqualifiedLoc());
5320     }
5321     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5322       TL.setNameLoc(DS.getTypeSpecTypeLoc());
5323     }
5324     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5325       TL.setNameLoc(DS.getTypeSpecTypeLoc());
5326       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5327       // addition field. What we have is good enough for dispay of location
5328       // of 'fixit' on interface name.
5329       TL.setNameEndLoc(DS.getLocEnd());
5330     }
5331     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5332       TypeSourceInfo *RepTInfo = nullptr;
5333       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5334       TL.copy(RepTInfo->getTypeLoc());
5335     }
5336     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5337       TypeSourceInfo *RepTInfo = nullptr;
5338       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5339       TL.copy(RepTInfo->getTypeLoc());
5340     }
5341     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5342       TypeSourceInfo *TInfo = nullptr;
5343       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5344 
5345       // If we got no declarator info from previous Sema routines,
5346       // just fill with the typespec loc.
5347       if (!TInfo) {
5348         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5349         return;
5350       }
5351 
5352       TypeLoc OldTL = TInfo->getTypeLoc();
5353       if (TInfo->getType()->getAs<ElaboratedType>()) {
5354         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5355         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5356             .castAs<TemplateSpecializationTypeLoc>();
5357         TL.copy(NamedTL);
5358       } else {
5359         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5360         assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5361       }
5362 
5363     }
5364     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5365       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5366       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5367       TL.setParensRange(DS.getTypeofParensRange());
5368     }
5369     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5370       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5371       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5372       TL.setParensRange(DS.getTypeofParensRange());
5373       assert(DS.getRepAsType());
5374       TypeSourceInfo *TInfo = nullptr;
5375       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5376       TL.setUnderlyingTInfo(TInfo);
5377     }
5378     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5379       // FIXME: This holds only because we only have one unary transform.
5380       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5381       TL.setKWLoc(DS.getTypeSpecTypeLoc());
5382       TL.setParensRange(DS.getTypeofParensRange());
5383       assert(DS.getRepAsType());
5384       TypeSourceInfo *TInfo = nullptr;
5385       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5386       TL.setUnderlyingTInfo(TInfo);
5387     }
5388     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5389       // By default, use the source location of the type specifier.
5390       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5391       if (TL.needsExtraLocalData()) {
5392         // Set info for the written builtin specifiers.
5393         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5394         // Try to have a meaningful source location.
5395         if (TL.getWrittenSignSpec() != TSS_unspecified)
5396           TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5397         if (TL.getWrittenWidthSpec() != TSW_unspecified)
5398           TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5399       }
5400     }
5401     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5402       ElaboratedTypeKeyword Keyword
5403         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5404       if (DS.getTypeSpecType() == TST_typename) {
5405         TypeSourceInfo *TInfo = nullptr;
5406         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5407         if (TInfo) {
5408           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5409           return;
5410         }
5411       }
5412       TL.setElaboratedKeywordLoc(Keyword != ETK_None
5413                                  ? DS.getTypeSpecTypeLoc()
5414                                  : SourceLocation());
5415       const CXXScopeSpec& SS = DS.getTypeSpecScope();
5416       TL.setQualifierLoc(SS.getWithLocInContext(Context));
5417       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5418     }
5419     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5420       assert(DS.getTypeSpecType() == TST_typename);
5421       TypeSourceInfo *TInfo = nullptr;
5422       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5423       assert(TInfo);
5424       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5425     }
5426     void VisitDependentTemplateSpecializationTypeLoc(
5427                                  DependentTemplateSpecializationTypeLoc TL) {
5428       assert(DS.getTypeSpecType() == TST_typename);
5429       TypeSourceInfo *TInfo = nullptr;
5430       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5431       assert(TInfo);
5432       TL.copy(
5433           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5434     }
5435     void VisitTagTypeLoc(TagTypeLoc TL) {
5436       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5437     }
5438     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5439       // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5440       // or an _Atomic qualifier.
5441       if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5442         TL.setKWLoc(DS.getTypeSpecTypeLoc());
5443         TL.setParensRange(DS.getTypeofParensRange());
5444 
5445         TypeSourceInfo *TInfo = nullptr;
5446         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5447         assert(TInfo);
5448         TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5449       } else {
5450         TL.setKWLoc(DS.getAtomicSpecLoc());
5451         // No parens, to indicate this was spelled as an _Atomic qualifier.
5452         TL.setParensRange(SourceRange());
5453         Visit(TL.getValueLoc());
5454       }
5455     }
5456 
5457     void VisitPipeTypeLoc(PipeTypeLoc TL) {
5458       TL.setKWLoc(DS.getTypeSpecTypeLoc());
5459 
5460       TypeSourceInfo *TInfo = nullptr;
5461       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5462       TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5463     }
5464 
5465     void VisitTypeLoc(TypeLoc TL) {
5466       // FIXME: add other typespec types and change this to an assert.
5467       TL.initialize(Context, DS.getTypeSpecTypeLoc());
5468     }
5469   };
5470 
5471   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5472     ASTContext &Context;
5473     const DeclaratorChunk &Chunk;
5474 
5475   public:
5476     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
5477       : Context(Context), Chunk(Chunk) {}
5478 
5479     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5480       llvm_unreachable("qualified type locs not expected here!");
5481     }
5482     void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5483       llvm_unreachable("decayed type locs not expected here!");
5484     }
5485 
5486     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5487       fillAttributedTypeLoc(TL, Chunk.getAttrs());
5488     }
5489     void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5490       // nothing
5491     }
5492     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5493       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5494       TL.setCaretLoc(Chunk.Loc);
5495     }
5496     void VisitPointerTypeLoc(PointerTypeLoc TL) {
5497       assert(Chunk.Kind == DeclaratorChunk::Pointer);
5498       TL.setStarLoc(Chunk.Loc);
5499     }
5500     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5501       assert(Chunk.Kind == DeclaratorChunk::Pointer);
5502       TL.setStarLoc(Chunk.Loc);
5503     }
5504     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5505       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5506       const CXXScopeSpec& SS = Chunk.Mem.Scope();
5507       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5508 
5509       const Type* ClsTy = TL.getClass();
5510       QualType ClsQT = QualType(ClsTy, 0);
5511       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5512       // Now copy source location info into the type loc component.
5513       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5514       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5515       case NestedNameSpecifier::Identifier:
5516         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5517         {
5518           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5519           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5520           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5521           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5522         }
5523         break;
5524 
5525       case NestedNameSpecifier::TypeSpec:
5526       case NestedNameSpecifier::TypeSpecWithTemplate:
5527         if (isa<ElaboratedType>(ClsTy)) {
5528           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5529           ETLoc.setElaboratedKeywordLoc(SourceLocation());
5530           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5531           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5532           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5533         } else {
5534           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5535         }
5536         break;
5537 
5538       case NestedNameSpecifier::Namespace:
5539       case NestedNameSpecifier::NamespaceAlias:
5540       case NestedNameSpecifier::Global:
5541       case NestedNameSpecifier::Super:
5542         llvm_unreachable("Nested-name-specifier must name a type");
5543       }
5544 
5545       // Finally fill in MemberPointerLocInfo fields.
5546       TL.setStarLoc(Chunk.Loc);
5547       TL.setClassTInfo(ClsTInfo);
5548     }
5549     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5550       assert(Chunk.Kind == DeclaratorChunk::Reference);
5551       // 'Amp' is misleading: this might have been originally
5552       /// spelled with AmpAmp.
5553       TL.setAmpLoc(Chunk.Loc);
5554     }
5555     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5556       assert(Chunk.Kind == DeclaratorChunk::Reference);
5557       assert(!Chunk.Ref.LValueRef);
5558       TL.setAmpAmpLoc(Chunk.Loc);
5559     }
5560     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5561       assert(Chunk.Kind == DeclaratorChunk::Array);
5562       TL.setLBracketLoc(Chunk.Loc);
5563       TL.setRBracketLoc(Chunk.EndLoc);
5564       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5565     }
5566     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5567       assert(Chunk.Kind == DeclaratorChunk::Function);
5568       TL.setLocalRangeBegin(Chunk.Loc);
5569       TL.setLocalRangeEnd(Chunk.EndLoc);
5570 
5571       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5572       TL.setLParenLoc(FTI.getLParenLoc());
5573       TL.setRParenLoc(FTI.getRParenLoc());
5574       for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5575         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5576         TL.setParam(tpi++, Param);
5577       }
5578       TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
5579     }
5580     void VisitParenTypeLoc(ParenTypeLoc TL) {
5581       assert(Chunk.Kind == DeclaratorChunk::Paren);
5582       TL.setLParenLoc(Chunk.Loc);
5583       TL.setRParenLoc(Chunk.EndLoc);
5584     }
5585     void VisitPipeTypeLoc(PipeTypeLoc TL) {
5586       assert(Chunk.Kind == DeclaratorChunk::Pipe);
5587       TL.setKWLoc(Chunk.Loc);
5588     }
5589 
5590     void VisitTypeLoc(TypeLoc TL) {
5591       llvm_unreachable("unsupported TypeLoc kind in declarator!");
5592     }
5593   };
5594 } // end anonymous namespace
5595 
5596 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5597   SourceLocation Loc;
5598   switch (Chunk.Kind) {
5599   case DeclaratorChunk::Function:
5600   case DeclaratorChunk::Array:
5601   case DeclaratorChunk::Paren:
5602   case DeclaratorChunk::Pipe:
5603     llvm_unreachable("cannot be _Atomic qualified");
5604 
5605   case DeclaratorChunk::Pointer:
5606     Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5607     break;
5608 
5609   case DeclaratorChunk::BlockPointer:
5610   case DeclaratorChunk::Reference:
5611   case DeclaratorChunk::MemberPointer:
5612     // FIXME: Provide a source location for the _Atomic keyword.
5613     break;
5614   }
5615 
5616   ATL.setKWLoc(Loc);
5617   ATL.setParensRange(SourceRange());
5618 }
5619 
5620 static void fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
5621                                              const AttributeList *Attrs) {
5622   while (Attrs && Attrs->getKind() != AttributeList::AT_AddressSpace)
5623     Attrs = Attrs->getNext();
5624 
5625   assert(Attrs && "no address_space attribute found at the expected location!");
5626 
5627   DASTL.setAttrNameLoc(Attrs->getLoc());
5628   DASTL.setAttrExprOperand(Attrs->getArgAsExpr(0));
5629   DASTL.setAttrOperandParensRange(SourceRange());
5630 }
5631 
5632 /// Create and instantiate a TypeSourceInfo with type source information.
5633 ///
5634 /// \param T QualType referring to the type as written in source code.
5635 ///
5636 /// \param ReturnTypeInfo For declarators whose return type does not show
5637 /// up in the normal place in the declaration specifiers (such as a C++
5638 /// conversion function), this pointer will refer to a type source information
5639 /// for that return type.
5640 TypeSourceInfo *
5641 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
5642                                      TypeSourceInfo *ReturnTypeInfo) {
5643   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
5644   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5645   const AttributeList *DeclAttrs = D.getAttributes();
5646 
5647   // Handle parameter packs whose type is a pack expansion.
5648   if (isa<PackExpansionType>(T)) {
5649     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5650     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5651   }
5652 
5653   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5654 
5655     if (DependentAddressSpaceTypeLoc DASTL =
5656         CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
5657       fillDependentAddressSpaceTypeLoc(DASTL, D.getTypeObject(i).getAttrs());
5658       CurrTL = DASTL.getPointeeTypeLoc().getUnqualifiedLoc();
5659     }
5660 
5661     // An AtomicTypeLoc might be produced by an atomic qualifier in this
5662     // declarator chunk.
5663     if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5664       fillAtomicQualLoc(ATL, D.getTypeObject(i));
5665       CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5666     }
5667 
5668     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5669       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
5670       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5671     }
5672 
5673     // FIXME: Ordering here?
5674     while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5675       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5676 
5677     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
5678     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5679   }
5680 
5681   // If we have different source information for the return type, use
5682   // that.  This really only applies to C++ conversion functions.
5683   if (ReturnTypeInfo) {
5684     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5685     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5686     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5687   } else {
5688     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
5689   }
5690 
5691   return TInfo;
5692 }
5693 
5694 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5695 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5696   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5697   // and Sema during declaration parsing. Try deallocating/caching them when
5698   // it's appropriate, instead of allocating them and keeping them around.
5699   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5700                                                        TypeAlignment);
5701   new (LocT) LocInfoType(T, TInfo);
5702   assert(LocT->getTypeClass() != T->getTypeClass() &&
5703          "LocInfoType's TypeClass conflicts with an existing Type class");
5704   return ParsedType::make(QualType(LocT, 0));
5705 }
5706 
5707 void LocInfoType::getAsStringInternal(std::string &Str,
5708                                       const PrintingPolicy &Policy) const {
5709   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5710          " was used directly instead of getting the QualType through"
5711          " GetTypeFromParser");
5712 }
5713 
5714 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5715   // C99 6.7.6: Type names have no identifier.  This is already validated by
5716   // the parser.
5717   assert(D.getIdentifier() == nullptr &&
5718          "Type name should have no identifier!");
5719 
5720   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5721   QualType T = TInfo->getType();
5722   if (D.isInvalidType())
5723     return true;
5724 
5725   // Make sure there are no unused decl attributes on the declarator.
5726   // We don't want to do this for ObjC parameters because we're going
5727   // to apply them to the actual parameter declaration.
5728   // Likewise, we don't want to do this for alias declarations, because
5729   // we are actually going to build a declaration from this eventually.
5730   if (D.getContext() != DeclaratorContext::ObjCParameterContext &&
5731       D.getContext() != DeclaratorContext::AliasDeclContext &&
5732       D.getContext() != DeclaratorContext::AliasTemplateContext)
5733     checkUnusedDeclAttributes(D);
5734 
5735   if (getLangOpts().CPlusPlus) {
5736     // Check that there are no default arguments (C++ only).
5737     CheckExtraCXXDefaultArguments(D);
5738   }
5739 
5740   return CreateParsedType(T, TInfo);
5741 }
5742 
5743 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5744   QualType T = Context.getObjCInstanceType();
5745   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5746   return CreateParsedType(T, TInfo);
5747 }
5748 
5749 //===----------------------------------------------------------------------===//
5750 // Type Attribute Processing
5751 //===----------------------------------------------------------------------===//
5752 
5753 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
5754 /// is uninstantiated. If instantiated it will apply the appropriate address space
5755 /// to the type. This function allows dependent template variables to be used in
5756 /// conjunction with the address_space attribute
5757 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
5758                                      SourceLocation AttrLoc) {
5759   if (!AddrSpace->isValueDependent()) {
5760 
5761     llvm::APSInt addrSpace(32);
5762     if (!AddrSpace->isIntegerConstantExpr(addrSpace, Context)) {
5763       Diag(AttrLoc, diag::err_attribute_argument_type)
5764           << "'address_space'" << AANT_ArgumentIntegerConstant
5765           << AddrSpace->getSourceRange();
5766       return QualType();
5767     }
5768 
5769     // Bounds checking.
5770     if (addrSpace.isSigned()) {
5771       if (addrSpace.isNegative()) {
5772         Diag(AttrLoc, diag::err_attribute_address_space_negative)
5773             << AddrSpace->getSourceRange();
5774         return QualType();
5775       }
5776       addrSpace.setIsSigned(false);
5777     }
5778 
5779     llvm::APSInt max(addrSpace.getBitWidth());
5780     max =
5781         Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
5782     if (addrSpace > max) {
5783       Diag(AttrLoc, diag::err_attribute_address_space_too_high)
5784           << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
5785       return QualType();
5786     }
5787 
5788     LangAS ASIdx =
5789         getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
5790 
5791     // If this type is already address space qualified with a different
5792     // address space, reject it.
5793     // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
5794     // by qualifiers for two or more different address spaces."
5795     if (T.getAddressSpace() != LangAS::Default) {
5796       if (T.getAddressSpace() != ASIdx) {
5797         Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5798         return QualType();
5799       } else
5800         // Emit a warning if they are identical; it's likely unintended.
5801         Diag(AttrLoc,
5802              diag::warn_attribute_address_multiple_identical_qualifiers);
5803     }
5804 
5805     return Context.getAddrSpaceQualType(T, ASIdx);
5806   }
5807 
5808   // A check with similar intentions as checking if a type already has an
5809   // address space except for on a dependent types, basically if the
5810   // current type is already a DependentAddressSpaceType then its already
5811   // lined up to have another address space on it and we can't have
5812   // multiple address spaces on the one pointer indirection
5813   if (T->getAs<DependentAddressSpaceType>()) {
5814     Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5815     return QualType();
5816   }
5817 
5818   return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
5819 }
5820 
5821 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5822 /// specified type.  The attribute contains 1 argument, the id of the address
5823 /// space for the type.
5824 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5825                                             const AttributeList &Attr, Sema &S){
5826   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5827   // qualified by an address-space qualifier."
5828   if (Type->isFunctionType()) {
5829     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5830     Attr.setInvalid();
5831     return;
5832   }
5833 
5834   LangAS ASIdx;
5835   if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5836 
5837     // Check the attribute arguments.
5838     if (Attr.getNumArgs() != 1) {
5839       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5840           << Attr.getName() << 1;
5841       Attr.setInvalid();
5842       return;
5843     }
5844 
5845     Expr *ASArgExpr;
5846     if (Attr.isArgIdent(0)) {
5847       // Special case where the argument is a template id.
5848       CXXScopeSpec SS;
5849       SourceLocation TemplateKWLoc;
5850       UnqualifiedId id;
5851       id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
5852 
5853       ExprResult AddrSpace = S.ActOnIdExpression(
5854           S.getCurScope(), SS, TemplateKWLoc, id, false, false);
5855       if (AddrSpace.isInvalid())
5856         return;
5857 
5858       ASArgExpr = static_cast<Expr *>(AddrSpace.get());
5859     } else {
5860       ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5861     }
5862 
5863     // Create the DependentAddressSpaceType or append an address space onto
5864     // the type.
5865     QualType T = S.BuildAddressSpaceAttr(Type, ASArgExpr, Attr.getLoc());
5866 
5867     if (!T.isNull())
5868       Type = T;
5869     else
5870       Attr.setInvalid();
5871   } else {
5872     // The keyword-based type attributes imply which address space to use.
5873     switch (Attr.getKind()) {
5874     case AttributeList::AT_OpenCLGlobalAddressSpace:
5875       ASIdx = LangAS::opencl_global; break;
5876     case AttributeList::AT_OpenCLLocalAddressSpace:
5877       ASIdx = LangAS::opencl_local; break;
5878     case AttributeList::AT_OpenCLConstantAddressSpace:
5879       ASIdx = LangAS::opencl_constant; break;
5880     case AttributeList::AT_OpenCLGenericAddressSpace:
5881       ASIdx = LangAS::opencl_generic; break;
5882     case AttributeList::AT_OpenCLPrivateAddressSpace:
5883       ASIdx = LangAS::opencl_private; break;
5884     default:
5885       llvm_unreachable("Invalid address space");
5886     }
5887 
5888     // If this type is already address space qualified with a different
5889     // address space, reject it.
5890     // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5891     // qualifiers for two or more different address spaces."
5892     if (Type.getAddressSpace() != LangAS::Default) {
5893       if (Type.getAddressSpace() != ASIdx) {
5894         S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5895         Attr.setInvalid();
5896         return;
5897       } else
5898         // Emit a warning if they are identical; it's likely unintended.
5899         S.Diag(Attr.getLoc(),
5900                diag::warn_attribute_address_multiple_identical_qualifiers);
5901     }
5902 
5903     Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5904   }
5905 }
5906 
5907 /// Does this type have a "direct" ownership qualifier?  That is,
5908 /// is it written like "__strong id", as opposed to something like
5909 /// "typeof(foo)", where that happens to be strong?
5910 static bool hasDirectOwnershipQualifier(QualType type) {
5911   // Fast path: no qualifier at all.
5912   assert(type.getQualifiers().hasObjCLifetime());
5913 
5914   while (true) {
5915     // __strong id
5916     if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5917       if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5918         return true;
5919 
5920       type = attr->getModifiedType();
5921 
5922     // X *__strong (...)
5923     } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5924       type = paren->getInnerType();
5925 
5926     // That's it for things we want to complain about.  In particular,
5927     // we do not want to look through typedefs, typeof(expr),
5928     // typeof(type), or any other way that the type is somehow
5929     // abstracted.
5930     } else {
5931 
5932       return false;
5933     }
5934   }
5935 }
5936 
5937 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5938 /// attribute on the specified type.
5939 ///
5940 /// Returns 'true' if the attribute was handled.
5941 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5942                                        AttributeList &attr,
5943                                        QualType &type) {
5944   bool NonObjCPointer = false;
5945 
5946   if (!type->isDependentType() && !type->isUndeducedType()) {
5947     if (const PointerType *ptr = type->getAs<PointerType>()) {
5948       QualType pointee = ptr->getPointeeType();
5949       if (pointee->isObjCRetainableType() || pointee->isPointerType())
5950         return false;
5951       // It is important not to lose the source info that there was an attribute
5952       // applied to non-objc pointer. We will create an attributed type but
5953       // its type will be the same as the original type.
5954       NonObjCPointer = true;
5955     } else if (!type->isObjCRetainableType()) {
5956       return false;
5957     }
5958 
5959     // Don't accept an ownership attribute in the declspec if it would
5960     // just be the return type of a block pointer.
5961     if (state.isProcessingDeclSpec()) {
5962       Declarator &D = state.getDeclarator();
5963       if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5964                                   /*onlyBlockPointers=*/true))
5965         return false;
5966     }
5967   }
5968 
5969   Sema &S = state.getSema();
5970   SourceLocation AttrLoc = attr.getLoc();
5971   if (AttrLoc.isMacroID())
5972     AttrLoc =
5973         S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
5974 
5975   if (!attr.isArgIdent(0)) {
5976     S.Diag(AttrLoc, diag::err_attribute_argument_type)
5977       << attr.getName() << AANT_ArgumentString;
5978     attr.setInvalid();
5979     return true;
5980   }
5981 
5982   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5983   Qualifiers::ObjCLifetime lifetime;
5984   if (II->isStr("none"))
5985     lifetime = Qualifiers::OCL_ExplicitNone;
5986   else if (II->isStr("strong"))
5987     lifetime = Qualifiers::OCL_Strong;
5988   else if (II->isStr("weak"))
5989     lifetime = Qualifiers::OCL_Weak;
5990   else if (II->isStr("autoreleasing"))
5991     lifetime = Qualifiers::OCL_Autoreleasing;
5992   else {
5993     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5994       << attr.getName() << II;
5995     attr.setInvalid();
5996     return true;
5997   }
5998 
5999   // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6000   // outside of ARC mode.
6001   if (!S.getLangOpts().ObjCAutoRefCount &&
6002       lifetime != Qualifiers::OCL_Weak &&
6003       lifetime != Qualifiers::OCL_ExplicitNone) {
6004     return true;
6005   }
6006 
6007   SplitQualType underlyingType = type.split();
6008 
6009   // Check for redundant/conflicting ownership qualifiers.
6010   if (Qualifiers::ObjCLifetime previousLifetime
6011         = type.getQualifiers().getObjCLifetime()) {
6012     // If it's written directly, that's an error.
6013     if (hasDirectOwnershipQualifier(type)) {
6014       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6015         << type;
6016       return true;
6017     }
6018 
6019     // Otherwise, if the qualifiers actually conflict, pull sugar off
6020     // and remove the ObjCLifetime qualifiers.
6021     if (previousLifetime != lifetime) {
6022       // It's possible to have multiple local ObjCLifetime qualifiers. We
6023       // can't stop after we reach a type that is directly qualified.
6024       const Type *prevTy = nullptr;
6025       while (!prevTy || prevTy != underlyingType.Ty) {
6026         prevTy = underlyingType.Ty;
6027         underlyingType = underlyingType.getSingleStepDesugaredType();
6028       }
6029       underlyingType.Quals.removeObjCLifetime();
6030     }
6031   }
6032 
6033   underlyingType.Quals.addObjCLifetime(lifetime);
6034 
6035   if (NonObjCPointer) {
6036     StringRef name = attr.getName()->getName();
6037     switch (lifetime) {
6038     case Qualifiers::OCL_None:
6039     case Qualifiers::OCL_ExplicitNone:
6040       break;
6041     case Qualifiers::OCL_Strong: name = "__strong"; break;
6042     case Qualifiers::OCL_Weak: name = "__weak"; break;
6043     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6044     }
6045     S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6046       << TDS_ObjCObjOrBlock << type;
6047   }
6048 
6049   // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6050   // because having both 'T' and '__unsafe_unretained T' exist in the type
6051   // system causes unfortunate widespread consistency problems.  (For example,
6052   // they're not considered compatible types, and we mangle them identicially
6053   // as template arguments.)  These problems are all individually fixable,
6054   // but it's easier to just not add the qualifier and instead sniff it out
6055   // in specific places using isObjCInertUnsafeUnretainedType().
6056   //
6057   // Doing this does means we miss some trivial consistency checks that
6058   // would've triggered in ARC, but that's better than trying to solve all
6059   // the coexistence problems with __unsafe_unretained.
6060   if (!S.getLangOpts().ObjCAutoRefCount &&
6061       lifetime == Qualifiers::OCL_ExplicitNone) {
6062     type = S.Context.getAttributedType(
6063                              AttributedType::attr_objc_inert_unsafe_unretained,
6064                                        type, type);
6065     return true;
6066   }
6067 
6068   QualType origType = type;
6069   if (!NonObjCPointer)
6070     type = S.Context.getQualifiedType(underlyingType);
6071 
6072   // If we have a valid source location for the attribute, use an
6073   // AttributedType instead.
6074   if (AttrLoc.isValid())
6075     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
6076                                        origType, type);
6077 
6078   auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6079                             unsigned diagnostic, QualType type) {
6080     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
6081       S.DelayedDiagnostics.add(
6082           sema::DelayedDiagnostic::makeForbiddenType(
6083               S.getSourceManager().getExpansionLoc(loc),
6084               diagnostic, type, /*ignored*/ 0));
6085     } else {
6086       S.Diag(loc, diagnostic);
6087     }
6088   };
6089 
6090   // Sometimes, __weak isn't allowed.
6091   if (lifetime == Qualifiers::OCL_Weak &&
6092       !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6093 
6094     // Use a specialized diagnostic if the runtime just doesn't support them.
6095     unsigned diagnostic =
6096       (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6097                                        : diag::err_arc_weak_no_runtime);
6098 
6099     // In any case, delay the diagnostic until we know what we're parsing.
6100     diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6101 
6102     attr.setInvalid();
6103     return true;
6104   }
6105 
6106   // Forbid __weak for class objects marked as
6107   // objc_arc_weak_reference_unavailable
6108   if (lifetime == Qualifiers::OCL_Weak) {
6109     if (const ObjCObjectPointerType *ObjT =
6110           type->getAs<ObjCObjectPointerType>()) {
6111       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6112         if (Class->isArcWeakrefUnavailable()) {
6113           S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6114           S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6115                  diag::note_class_declared);
6116         }
6117       }
6118     }
6119   }
6120 
6121   return true;
6122 }
6123 
6124 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6125 /// attribute on the specified type.  Returns true to indicate that
6126 /// the attribute was handled, false to indicate that the type does
6127 /// not permit the attribute.
6128 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
6129                                  AttributeList &attr,
6130                                  QualType &type) {
6131   Sema &S = state.getSema();
6132 
6133   // Delay if this isn't some kind of pointer.
6134   if (!type->isPointerType() &&
6135       !type->isObjCObjectPointerType() &&
6136       !type->isBlockPointerType())
6137     return false;
6138 
6139   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6140     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6141     attr.setInvalid();
6142     return true;
6143   }
6144 
6145   // Check the attribute arguments.
6146   if (!attr.isArgIdent(0)) {
6147     S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6148       << attr.getName() << AANT_ArgumentString;
6149     attr.setInvalid();
6150     return true;
6151   }
6152   Qualifiers::GC GCAttr;
6153   if (attr.getNumArgs() > 1) {
6154     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6155       << attr.getName() << 1;
6156     attr.setInvalid();
6157     return true;
6158   }
6159 
6160   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6161   if (II->isStr("weak"))
6162     GCAttr = Qualifiers::Weak;
6163   else if (II->isStr("strong"))
6164     GCAttr = Qualifiers::Strong;
6165   else {
6166     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6167       << attr.getName() << II;
6168     attr.setInvalid();
6169     return true;
6170   }
6171 
6172   QualType origType = type;
6173   type = S.Context.getObjCGCQualType(origType, GCAttr);
6174 
6175   // Make an attributed type to preserve the source information.
6176   if (attr.getLoc().isValid())
6177     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
6178                                        origType, type);
6179 
6180   return true;
6181 }
6182 
6183 namespace {
6184   /// A helper class to unwrap a type down to a function for the
6185   /// purposes of applying attributes there.
6186   ///
6187   /// Use:
6188   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
6189   ///   if (unwrapped.isFunctionType()) {
6190   ///     const FunctionType *fn = unwrapped.get();
6191   ///     // change fn somehow
6192   ///     T = unwrapped.wrap(fn);
6193   ///   }
6194   struct FunctionTypeUnwrapper {
6195     enum WrapKind {
6196       Desugar,
6197       Attributed,
6198       Parens,
6199       Pointer,
6200       BlockPointer,
6201       Reference,
6202       MemberPointer
6203     };
6204 
6205     QualType Original;
6206     const FunctionType *Fn;
6207     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6208 
6209     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6210       while (true) {
6211         const Type *Ty = T.getTypePtr();
6212         if (isa<FunctionType>(Ty)) {
6213           Fn = cast<FunctionType>(Ty);
6214           return;
6215         } else if (isa<ParenType>(Ty)) {
6216           T = cast<ParenType>(Ty)->getInnerType();
6217           Stack.push_back(Parens);
6218         } else if (isa<PointerType>(Ty)) {
6219           T = cast<PointerType>(Ty)->getPointeeType();
6220           Stack.push_back(Pointer);
6221         } else if (isa<BlockPointerType>(Ty)) {
6222           T = cast<BlockPointerType>(Ty)->getPointeeType();
6223           Stack.push_back(BlockPointer);
6224         } else if (isa<MemberPointerType>(Ty)) {
6225           T = cast<MemberPointerType>(Ty)->getPointeeType();
6226           Stack.push_back(MemberPointer);
6227         } else if (isa<ReferenceType>(Ty)) {
6228           T = cast<ReferenceType>(Ty)->getPointeeType();
6229           Stack.push_back(Reference);
6230         } else if (isa<AttributedType>(Ty)) {
6231           T = cast<AttributedType>(Ty)->getEquivalentType();
6232           Stack.push_back(Attributed);
6233         } else {
6234           const Type *DTy = Ty->getUnqualifiedDesugaredType();
6235           if (Ty == DTy) {
6236             Fn = nullptr;
6237             return;
6238           }
6239 
6240           T = QualType(DTy, 0);
6241           Stack.push_back(Desugar);
6242         }
6243       }
6244     }
6245 
6246     bool isFunctionType() const { return (Fn != nullptr); }
6247     const FunctionType *get() const { return Fn; }
6248 
6249     QualType wrap(Sema &S, const FunctionType *New) {
6250       // If T wasn't modified from the unwrapped type, do nothing.
6251       if (New == get()) return Original;
6252 
6253       Fn = New;
6254       return wrap(S.Context, Original, 0);
6255     }
6256 
6257   private:
6258     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6259       if (I == Stack.size())
6260         return C.getQualifiedType(Fn, Old.getQualifiers());
6261 
6262       // Build up the inner type, applying the qualifiers from the old
6263       // type to the new type.
6264       SplitQualType SplitOld = Old.split();
6265 
6266       // As a special case, tail-recurse if there are no qualifiers.
6267       if (SplitOld.Quals.empty())
6268         return wrap(C, SplitOld.Ty, I);
6269       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6270     }
6271 
6272     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6273       if (I == Stack.size()) return QualType(Fn, 0);
6274 
6275       switch (static_cast<WrapKind>(Stack[I++])) {
6276       case Desugar:
6277         // This is the point at which we potentially lose source
6278         // information.
6279         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6280 
6281       case Attributed:
6282         return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
6283 
6284       case Parens: {
6285         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
6286         return C.getParenType(New);
6287       }
6288 
6289       case Pointer: {
6290         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
6291         return C.getPointerType(New);
6292       }
6293 
6294       case BlockPointer: {
6295         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
6296         return C.getBlockPointerType(New);
6297       }
6298 
6299       case MemberPointer: {
6300         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
6301         QualType New = wrap(C, OldMPT->getPointeeType(), I);
6302         return C.getMemberPointerType(New, OldMPT->getClass());
6303       }
6304 
6305       case Reference: {
6306         const ReferenceType *OldRef = cast<ReferenceType>(Old);
6307         QualType New = wrap(C, OldRef->getPointeeType(), I);
6308         if (isa<LValueReferenceType>(OldRef))
6309           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
6310         else
6311           return C.getRValueReferenceType(New);
6312       }
6313       }
6314 
6315       llvm_unreachable("unknown wrapping kind");
6316     }
6317   };
6318 } // end anonymous namespace
6319 
6320 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
6321                                              AttributeList &Attr,
6322                                              QualType &Type) {
6323   Sema &S = State.getSema();
6324 
6325   AttributeList::Kind Kind = Attr.getKind();
6326   QualType Desugared = Type;
6327   const AttributedType *AT = dyn_cast<AttributedType>(Type);
6328   while (AT) {
6329     AttributedType::Kind CurAttrKind = AT->getAttrKind();
6330 
6331     // You cannot specify duplicate type attributes, so if the attribute has
6332     // already been applied, flag it.
6333     if (getAttrListKind(CurAttrKind) == Kind) {
6334       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
6335         << Attr.getName();
6336       return true;
6337     }
6338 
6339     // You cannot have both __sptr and __uptr on the same type, nor can you
6340     // have __ptr32 and __ptr64.
6341     if ((CurAttrKind == AttributedType::attr_ptr32 &&
6342          Kind == AttributeList::AT_Ptr64) ||
6343         (CurAttrKind == AttributedType::attr_ptr64 &&
6344          Kind == AttributeList::AT_Ptr32)) {
6345       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6346         << "'__ptr32'" << "'__ptr64'";
6347       return true;
6348     } else if ((CurAttrKind == AttributedType::attr_sptr &&
6349                 Kind == AttributeList::AT_UPtr) ||
6350                (CurAttrKind == AttributedType::attr_uptr &&
6351                 Kind == AttributeList::AT_SPtr)) {
6352       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6353         << "'__sptr'" << "'__uptr'";
6354       return true;
6355     }
6356 
6357     Desugared = AT->getEquivalentType();
6358     AT = dyn_cast<AttributedType>(Desugared);
6359   }
6360 
6361   // Pointer type qualifiers can only operate on pointer types, but not
6362   // pointer-to-member types.
6363   if (!isa<PointerType>(Desugared)) {
6364     if (Type->isMemberPointerType())
6365       S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
6366           << Attr.getName();
6367     else
6368       S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
6369           << Attr.getName() << 0;
6370     return true;
6371   }
6372 
6373   AttributedType::Kind TAK;
6374   switch (Kind) {
6375   default: llvm_unreachable("Unknown attribute kind");
6376   case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
6377   case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
6378   case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
6379   case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
6380   }
6381 
6382   Type = S.Context.getAttributedType(TAK, Type, Type);
6383   return false;
6384 }
6385 
6386 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
6387                                          NullabilityKind nullability,
6388                                          SourceLocation nullabilityLoc,
6389                                          bool isContextSensitive,
6390                                          bool allowOnArrayType) {
6391   recordNullabilitySeen(*this, nullabilityLoc);
6392 
6393   // Check for existing nullability attributes on the type.
6394   QualType desugared = type;
6395   while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6396     // Check whether there is already a null
6397     if (auto existingNullability = attributed->getImmediateNullability()) {
6398       // Duplicated nullability.
6399       if (nullability == *existingNullability) {
6400         Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6401           << DiagNullabilityKind(nullability, isContextSensitive)
6402           << FixItHint::CreateRemoval(nullabilityLoc);
6403 
6404         break;
6405       }
6406 
6407       // Conflicting nullability.
6408       Diag(nullabilityLoc, diag::err_nullability_conflicting)
6409         << DiagNullabilityKind(nullability, isContextSensitive)
6410         << DiagNullabilityKind(*existingNullability, false);
6411       return true;
6412     }
6413 
6414     desugared = attributed->getModifiedType();
6415   }
6416 
6417   // If there is already a different nullability specifier, complain.
6418   // This (unlike the code above) looks through typedefs that might
6419   // have nullability specifiers on them, which means we cannot
6420   // provide a useful Fix-It.
6421   if (auto existingNullability = desugared->getNullability(Context)) {
6422     if (nullability != *existingNullability) {
6423       Diag(nullabilityLoc, diag::err_nullability_conflicting)
6424         << DiagNullabilityKind(nullability, isContextSensitive)
6425         << DiagNullabilityKind(*existingNullability, false);
6426 
6427       // Try to find the typedef with the existing nullability specifier.
6428       if (auto typedefType = desugared->getAs<TypedefType>()) {
6429         TypedefNameDecl *typedefDecl = typedefType->getDecl();
6430         QualType underlyingType = typedefDecl->getUnderlyingType();
6431         if (auto typedefNullability
6432               = AttributedType::stripOuterNullability(underlyingType)) {
6433           if (*typedefNullability == *existingNullability) {
6434             Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6435               << DiagNullabilityKind(*existingNullability, false);
6436           }
6437         }
6438       }
6439 
6440       return true;
6441     }
6442   }
6443 
6444   // If this definitely isn't a pointer type, reject the specifier.
6445   if (!desugared->canHaveNullability() &&
6446       !(allowOnArrayType && desugared->isArrayType())) {
6447     Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6448       << DiagNullabilityKind(nullability, isContextSensitive) << type;
6449     return true;
6450   }
6451 
6452   // For the context-sensitive keywords/Objective-C property
6453   // attributes, require that the type be a single-level pointer.
6454   if (isContextSensitive) {
6455     // Make sure that the pointee isn't itself a pointer type.
6456     const Type *pointeeType;
6457     if (desugared->isArrayType())
6458       pointeeType = desugared->getArrayElementTypeNoTypeQual();
6459     else
6460       pointeeType = desugared->getPointeeType().getTypePtr();
6461 
6462     if (pointeeType->isAnyPointerType() ||
6463         pointeeType->isObjCObjectPointerType() ||
6464         pointeeType->isMemberPointerType()) {
6465       Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6466         << DiagNullabilityKind(nullability, true)
6467         << type;
6468       Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6469         << DiagNullabilityKind(nullability, false)
6470         << type
6471         << FixItHint::CreateReplacement(nullabilityLoc,
6472                                         getNullabilitySpelling(nullability));
6473       return true;
6474     }
6475   }
6476 
6477   // Form the attributed type.
6478   type = Context.getAttributedType(
6479            AttributedType::getNullabilityAttrKind(nullability), type, type);
6480   return false;
6481 }
6482 
6483 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
6484   if (isa<ObjCTypeParamType>(type)) {
6485     // Build the attributed type to record where __kindof occurred.
6486     type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6487                                      type, type);
6488     return false;
6489   }
6490 
6491   // Find out if it's an Objective-C object or object pointer type;
6492   const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6493   const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6494                                           : type->getAs<ObjCObjectType>();
6495 
6496   // If not, we can't apply __kindof.
6497   if (!objType) {
6498     // FIXME: Handle dependent types that aren't yet object types.
6499     Diag(loc, diag::err_objc_kindof_nonobject)
6500       << type;
6501     return true;
6502   }
6503 
6504   // Rebuild the "equivalent" type, which pushes __kindof down into
6505   // the object type.
6506   // There is no need to apply kindof on an unqualified id type.
6507   QualType equivType = Context.getObjCObjectType(
6508       objType->getBaseType(), objType->getTypeArgsAsWritten(),
6509       objType->getProtocols(),
6510       /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6511 
6512   // If we started with an object pointer type, rebuild it.
6513   if (ptrType) {
6514     equivType = Context.getObjCObjectPointerType(equivType);
6515     if (auto nullability = type->getNullability(Context)) {
6516       auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
6517       equivType = Context.getAttributedType(attrKind, equivType, equivType);
6518     }
6519   }
6520 
6521   // Build the attributed type to record where __kindof occurred.
6522   type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6523                                    type,
6524                                    equivType);
6525 
6526   return false;
6527 }
6528 
6529 /// Map a nullability attribute kind to a nullability kind.
6530 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
6531   switch (kind) {
6532   case AttributeList::AT_TypeNonNull:
6533     return NullabilityKind::NonNull;
6534 
6535   case AttributeList::AT_TypeNullable:
6536     return NullabilityKind::Nullable;
6537 
6538   case AttributeList::AT_TypeNullUnspecified:
6539     return NullabilityKind::Unspecified;
6540 
6541   default:
6542     llvm_unreachable("not a nullability attribute kind");
6543   }
6544 }
6545 
6546 /// Distribute a nullability type attribute that cannot be applied to
6547 /// the type specifier to a pointer, block pointer, or member pointer
6548 /// declarator, complaining if necessary.
6549 ///
6550 /// \returns true if the nullability annotation was distributed, false
6551 /// otherwise.
6552 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6553                                           QualType type,
6554                                           AttributeList &attr) {
6555   Declarator &declarator = state.getDeclarator();
6556 
6557   /// Attempt to move the attribute to the specified chunk.
6558   auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6559     // If there is already a nullability attribute there, don't add
6560     // one.
6561     if (hasNullabilityAttr(chunk.getAttrListRef()))
6562       return false;
6563 
6564     // Complain about the nullability qualifier being in the wrong
6565     // place.
6566     enum {
6567       PK_Pointer,
6568       PK_BlockPointer,
6569       PK_MemberPointer,
6570       PK_FunctionPointer,
6571       PK_MemberFunctionPointer,
6572     } pointerKind
6573       = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6574                                                              : PK_Pointer)
6575         : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6576         : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6577 
6578     auto diag = state.getSema().Diag(attr.getLoc(),
6579                                      diag::warn_nullability_declspec)
6580       << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6581                              attr.isContextSensitiveKeywordAttribute())
6582       << type
6583       << static_cast<unsigned>(pointerKind);
6584 
6585     // FIXME: MemberPointer chunks don't carry the location of the *.
6586     if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6587       diag << FixItHint::CreateRemoval(attr.getLoc())
6588            << FixItHint::CreateInsertion(
6589                 state.getSema().getPreprocessor()
6590                   .getLocForEndOfToken(chunk.Loc),
6591                 " " + attr.getName()->getName().str() + " ");
6592     }
6593 
6594     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
6595                            chunk.getAttrListRef());
6596     return true;
6597   };
6598 
6599   // Move it to the outermost pointer, member pointer, or block
6600   // pointer declarator.
6601   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6602     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6603     switch (chunk.Kind) {
6604     case DeclaratorChunk::Pointer:
6605     case DeclaratorChunk::BlockPointer:
6606     case DeclaratorChunk::MemberPointer:
6607       return moveToChunk(chunk, false);
6608 
6609     case DeclaratorChunk::Paren:
6610     case DeclaratorChunk::Array:
6611       continue;
6612 
6613     case DeclaratorChunk::Function:
6614       // Try to move past the return type to a function/block/member
6615       // function pointer.
6616       if (DeclaratorChunk *dest = maybeMovePastReturnType(
6617                                     declarator, i,
6618                                     /*onlyBlockPointers=*/false)) {
6619         return moveToChunk(*dest, true);
6620       }
6621 
6622       return false;
6623 
6624     // Don't walk through these.
6625     case DeclaratorChunk::Reference:
6626     case DeclaratorChunk::Pipe:
6627       return false;
6628     }
6629   }
6630 
6631   return false;
6632 }
6633 
6634 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
6635   assert(!Attr.isInvalid());
6636   switch (Attr.getKind()) {
6637   default:
6638     llvm_unreachable("not a calling convention attribute");
6639   case AttributeList::AT_CDecl:
6640     return AttributedType::attr_cdecl;
6641   case AttributeList::AT_FastCall:
6642     return AttributedType::attr_fastcall;
6643   case AttributeList::AT_StdCall:
6644     return AttributedType::attr_stdcall;
6645   case AttributeList::AT_ThisCall:
6646     return AttributedType::attr_thiscall;
6647   case AttributeList::AT_RegCall:
6648     return AttributedType::attr_regcall;
6649   case AttributeList::AT_Pascal:
6650     return AttributedType::attr_pascal;
6651   case AttributeList::AT_SwiftCall:
6652     return AttributedType::attr_swiftcall;
6653   case AttributeList::AT_VectorCall:
6654     return AttributedType::attr_vectorcall;
6655   case AttributeList::AT_Pcs: {
6656     // The attribute may have had a fixit applied where we treated an
6657     // identifier as a string literal.  The contents of the string are valid,
6658     // but the form may not be.
6659     StringRef Str;
6660     if (Attr.isArgExpr(0))
6661       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6662     else
6663       Str = Attr.getArgAsIdent(0)->Ident->getName();
6664     return llvm::StringSwitch<AttributedType::Kind>(Str)
6665         .Case("aapcs", AttributedType::attr_pcs)
6666         .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6667   }
6668   case AttributeList::AT_IntelOclBicc:
6669     return AttributedType::attr_inteloclbicc;
6670   case AttributeList::AT_MSABI:
6671     return AttributedType::attr_ms_abi;
6672   case AttributeList::AT_SysVABI:
6673     return AttributedType::attr_sysv_abi;
6674   case AttributeList::AT_PreserveMost:
6675     return AttributedType::attr_preserve_most;
6676   case AttributeList::AT_PreserveAll:
6677     return AttributedType::attr_preserve_all;
6678   }
6679   llvm_unreachable("unexpected attribute kind!");
6680 }
6681 
6682 /// Process an individual function attribute.  Returns true to
6683 /// indicate that the attribute was handled, false if it wasn't.
6684 static bool handleFunctionTypeAttr(TypeProcessingState &state,
6685                                    AttributeList &attr,
6686                                    QualType &type) {
6687   Sema &S = state.getSema();
6688 
6689   FunctionTypeUnwrapper unwrapped(S, type);
6690 
6691   if (attr.getKind() == AttributeList::AT_NoReturn) {
6692     if (S.CheckAttrNoArgs(attr))
6693       return true;
6694 
6695     // Delay if this is not a function type.
6696     if (!unwrapped.isFunctionType())
6697       return false;
6698 
6699     // Otherwise we can process right away.
6700     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6701     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6702     return true;
6703   }
6704 
6705   // ns_returns_retained is not always a type attribute, but if we got
6706   // here, we're treating it as one right now.
6707   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
6708     if (attr.getNumArgs()) return true;
6709 
6710     // Delay if this is not a function type.
6711     if (!unwrapped.isFunctionType())
6712       return false;
6713 
6714     // Check whether the return type is reasonable.
6715     if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
6716                                            unwrapped.get()->getReturnType()))
6717       return true;
6718 
6719     // Only actually change the underlying type in ARC builds.
6720     QualType origType = type;
6721     if (state.getSema().getLangOpts().ObjCAutoRefCount) {
6722       FunctionType::ExtInfo EI
6723         = unwrapped.get()->getExtInfo().withProducesResult(true);
6724       type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6725     }
6726     type = S.Context.getAttributedType(AttributedType::attr_ns_returns_retained,
6727                                        origType, type);
6728     return true;
6729   }
6730 
6731   if (attr.getKind() == AttributeList::AT_AnyX86NoCallerSavedRegisters) {
6732     if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
6733       return true;
6734 
6735     // Delay if this is not a function type.
6736     if (!unwrapped.isFunctionType())
6737       return false;
6738 
6739     FunctionType::ExtInfo EI =
6740         unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
6741     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6742     return true;
6743   }
6744 
6745   if (attr.getKind() == AttributeList::AT_AnyX86NoCfCheck) {
6746     if (!S.getLangOpts().CFProtectionBranch) {
6747       S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
6748       attr.setInvalid();
6749       return true;
6750     }
6751 
6752     if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
6753       return true;
6754 
6755     // If this is not a function type, warning will be asserted by subject
6756     // check.
6757     if (!unwrapped.isFunctionType())
6758       return true;
6759 
6760     FunctionType::ExtInfo EI =
6761       unwrapped.get()->getExtInfo().withNoCfCheck(true);
6762     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6763     return true;
6764   }
6765 
6766   if (attr.getKind() == AttributeList::AT_Regparm) {
6767     unsigned value;
6768     if (S.CheckRegparmAttr(attr, value))
6769       return true;
6770 
6771     // Delay if this is not a function type.
6772     if (!unwrapped.isFunctionType())
6773       return false;
6774 
6775     // Diagnose regparm with fastcall.
6776     const FunctionType *fn = unwrapped.get();
6777     CallingConv CC = fn->getCallConv();
6778     if (CC == CC_X86FastCall) {
6779       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6780         << FunctionType::getNameForCallConv(CC)
6781         << "regparm";
6782       attr.setInvalid();
6783       return true;
6784     }
6785 
6786     FunctionType::ExtInfo EI =
6787       unwrapped.get()->getExtInfo().withRegParm(value);
6788     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6789     return true;
6790   }
6791 
6792   // Delay if the type didn't work out to a function.
6793   if (!unwrapped.isFunctionType()) return false;
6794 
6795   // Otherwise, a calling convention.
6796   CallingConv CC;
6797   if (S.CheckCallingConvAttr(attr, CC))
6798     return true;
6799 
6800   const FunctionType *fn = unwrapped.get();
6801   CallingConv CCOld = fn->getCallConv();
6802   AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6803 
6804   if (CCOld != CC) {
6805     // Error out on when there's already an attribute on the type
6806     // and the CCs don't match.
6807     const AttributedType *AT = S.getCallingConvAttributedType(type);
6808     if (AT && AT->getAttrKind() != CCAttrKind) {
6809       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6810         << FunctionType::getNameForCallConv(CC)
6811         << FunctionType::getNameForCallConv(CCOld);
6812       attr.setInvalid();
6813       return true;
6814     }
6815   }
6816 
6817   // Diagnose use of variadic functions with calling conventions that
6818   // don't support them (e.g. because they're callee-cleanup).
6819   // We delay warning about this on unprototyped function declarations
6820   // until after redeclaration checking, just in case we pick up a
6821   // prototype that way.  And apparently we also "delay" warning about
6822   // unprototyped function types in general, despite not necessarily having
6823   // much ability to diagnose it later.
6824   if (!supportsVariadicCall(CC)) {
6825     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6826     if (FnP && FnP->isVariadic()) {
6827       unsigned DiagID = diag::err_cconv_varargs;
6828 
6829       // stdcall and fastcall are ignored with a warning for GCC and MS
6830       // compatibility.
6831       bool IsInvalid = true;
6832       if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6833         DiagID = diag::warn_cconv_varargs;
6834         IsInvalid = false;
6835       }
6836 
6837       S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6838       if (IsInvalid) attr.setInvalid();
6839       return true;
6840     }
6841   }
6842 
6843   // Also diagnose fastcall with regparm.
6844   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6845     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6846         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6847     attr.setInvalid();
6848     return true;
6849   }
6850 
6851   // Modify the CC from the wrapped function type, wrap it all back, and then
6852   // wrap the whole thing in an AttributedType as written.  The modified type
6853   // might have a different CC if we ignored the attribute.
6854   QualType Equivalent;
6855   if (CCOld == CC) {
6856     Equivalent = type;
6857   } else {
6858     auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6859     Equivalent =
6860       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6861   }
6862   type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6863   return true;
6864 }
6865 
6866 bool Sema::hasExplicitCallingConv(QualType &T) {
6867   QualType R = T.IgnoreParens();
6868   while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6869     if (AT->isCallingConv())
6870       return true;
6871     R = AT->getModifiedType().IgnoreParens();
6872   }
6873   return false;
6874 }
6875 
6876 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6877                                   SourceLocation Loc) {
6878   FunctionTypeUnwrapper Unwrapped(*this, T);
6879   const FunctionType *FT = Unwrapped.get();
6880   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6881                      cast<FunctionProtoType>(FT)->isVariadic());
6882   CallingConv CurCC = FT->getCallConv();
6883   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6884 
6885   if (CurCC == ToCC)
6886     return;
6887 
6888   // MS compiler ignores explicit calling convention attributes on structors. We
6889   // should do the same.
6890   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6891     // Issue a warning on ignored calling convention -- except of __stdcall.
6892     // Again, this is what MS compiler does.
6893     if (CurCC != CC_X86StdCall)
6894       Diag(Loc, diag::warn_cconv_structors)
6895           << FunctionType::getNameForCallConv(CurCC);
6896   // Default adjustment.
6897   } else {
6898     // Only adjust types with the default convention.  For example, on Windows
6899     // we should adjust a __cdecl type to __thiscall for instance methods, and a
6900     // __thiscall type to __cdecl for static methods.
6901     CallingConv DefaultCC =
6902         Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6903 
6904     if (CurCC != DefaultCC || DefaultCC == ToCC)
6905       return;
6906 
6907     if (hasExplicitCallingConv(T))
6908       return;
6909   }
6910 
6911   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6912   QualType Wrapped = Unwrapped.wrap(*this, FT);
6913   T = Context.getAdjustedType(T, Wrapped);
6914 }
6915 
6916 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6917 /// and float scalars, although arrays, pointers, and function return values are
6918 /// allowed in conjunction with this construct. Aggregates with this attribute
6919 /// are invalid, even if they are of the same size as a corresponding scalar.
6920 /// The raw attribute should contain precisely 1 argument, the vector size for
6921 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6922 /// this routine will return a new vector type.
6923 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6924                                  Sema &S) {
6925   // Check the attribute arguments.
6926   if (Attr.getNumArgs() != 1) {
6927     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6928       << Attr.getName() << 1;
6929     Attr.setInvalid();
6930     return;
6931   }
6932   Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6933   llvm::APSInt vecSize(32);
6934   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6935       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6936     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6937       << Attr.getName() << AANT_ArgumentIntegerConstant
6938       << sizeExpr->getSourceRange();
6939     Attr.setInvalid();
6940     return;
6941   }
6942   // The base type must be integer (not Boolean or enumeration) or float, and
6943   // can't already be a vector.
6944   if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6945       (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6946     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6947     Attr.setInvalid();
6948     return;
6949   }
6950   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6951   // vecSize is specified in bytes - convert to bits.
6952   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6953 
6954   // the vector size needs to be an integral multiple of the type size.
6955   if (vectorSize % typeSize) {
6956     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6957       << sizeExpr->getSourceRange();
6958     Attr.setInvalid();
6959     return;
6960   }
6961   if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6962     S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6963       << sizeExpr->getSourceRange();
6964     Attr.setInvalid();
6965     return;
6966   }
6967   if (vectorSize == 0) {
6968     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6969       << sizeExpr->getSourceRange();
6970     Attr.setInvalid();
6971     return;
6972   }
6973 
6974   // Success! Instantiate the vector type, the number of elements is > 0, and
6975   // not required to be a power of 2, unlike GCC.
6976   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6977                                     VectorType::GenericVector);
6978 }
6979 
6980 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
6981 /// a type.
6982 static void HandleExtVectorTypeAttr(QualType &CurType,
6983                                     const AttributeList &Attr,
6984                                     Sema &S) {
6985   // check the attribute arguments.
6986   if (Attr.getNumArgs() != 1) {
6987     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6988       << Attr.getName() << 1;
6989     return;
6990   }
6991 
6992   Expr *sizeExpr;
6993 
6994   // Special case where the argument is a template id.
6995   if (Attr.isArgIdent(0)) {
6996     CXXScopeSpec SS;
6997     SourceLocation TemplateKWLoc;
6998     UnqualifiedId id;
6999     id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
7000 
7001     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
7002                                           id, false, false);
7003     if (Size.isInvalid())
7004       return;
7005 
7006     sizeExpr = Size.get();
7007   } else {
7008     sizeExpr = Attr.getArgAsExpr(0);
7009   }
7010 
7011   // Create the vector type.
7012   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
7013   if (!T.isNull())
7014     CurType = T;
7015 }
7016 
7017 static bool isPermittedNeonBaseType(QualType &Ty,
7018                                     VectorType::VectorKind VecKind, Sema &S) {
7019   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
7020   if (!BTy)
7021     return false;
7022 
7023   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
7024 
7025   // Signed poly is mathematically wrong, but has been baked into some ABIs by
7026   // now.
7027   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
7028                         Triple.getArch() == llvm::Triple::aarch64_be;
7029   if (VecKind == VectorType::NeonPolyVector) {
7030     if (IsPolyUnsigned) {
7031       // AArch64 polynomial vectors are unsigned and support poly64.
7032       return BTy->getKind() == BuiltinType::UChar ||
7033              BTy->getKind() == BuiltinType::UShort ||
7034              BTy->getKind() == BuiltinType::ULong ||
7035              BTy->getKind() == BuiltinType::ULongLong;
7036     } else {
7037       // AArch32 polynomial vector are signed.
7038       return BTy->getKind() == BuiltinType::SChar ||
7039              BTy->getKind() == BuiltinType::Short;
7040     }
7041   }
7042 
7043   // Non-polynomial vector types: the usual suspects are allowed, as well as
7044   // float64_t on AArch64.
7045   bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
7046                  Triple.getArch() == llvm::Triple::aarch64_be;
7047 
7048   if (Is64Bit && BTy->getKind() == BuiltinType::Double)
7049     return true;
7050 
7051   return BTy->getKind() == BuiltinType::SChar ||
7052          BTy->getKind() == BuiltinType::UChar ||
7053          BTy->getKind() == BuiltinType::Short ||
7054          BTy->getKind() == BuiltinType::UShort ||
7055          BTy->getKind() == BuiltinType::Int ||
7056          BTy->getKind() == BuiltinType::UInt ||
7057          BTy->getKind() == BuiltinType::Long ||
7058          BTy->getKind() == BuiltinType::ULong ||
7059          BTy->getKind() == BuiltinType::LongLong ||
7060          BTy->getKind() == BuiltinType::ULongLong ||
7061          BTy->getKind() == BuiltinType::Float ||
7062          BTy->getKind() == BuiltinType::Half;
7063 }
7064 
7065 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
7066 /// "neon_polyvector_type" attributes are used to create vector types that
7067 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
7068 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
7069 /// the argument to these Neon attributes is the number of vector elements,
7070 /// not the vector size in bytes.  The vector width and element type must
7071 /// match one of the standard Neon vector types.
7072 static void HandleNeonVectorTypeAttr(QualType& CurType,
7073                                      const AttributeList &Attr, Sema &S,
7074                                      VectorType::VectorKind VecKind) {
7075   // Target must have NEON
7076   if (!S.Context.getTargetInfo().hasFeature("neon")) {
7077     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
7078     Attr.setInvalid();
7079     return;
7080   }
7081   // Check the attribute arguments.
7082   if (Attr.getNumArgs() != 1) {
7083     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
7084       << Attr.getName() << 1;
7085     Attr.setInvalid();
7086     return;
7087   }
7088   // The number of elements must be an ICE.
7089   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
7090   llvm::APSInt numEltsInt(32);
7091   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
7092       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
7093     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
7094       << Attr.getName() << AANT_ArgumentIntegerConstant
7095       << numEltsExpr->getSourceRange();
7096     Attr.setInvalid();
7097     return;
7098   }
7099   // Only certain element types are supported for Neon vectors.
7100   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
7101     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
7102     Attr.setInvalid();
7103     return;
7104   }
7105 
7106   // The total size of the vector must be 64 or 128 bits.
7107   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
7108   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
7109   unsigned vecSize = typeSize * numElts;
7110   if (vecSize != 64 && vecSize != 128) {
7111     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
7112     Attr.setInvalid();
7113     return;
7114   }
7115 
7116   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
7117 }
7118 
7119 /// Handle OpenCL Access Qualifier Attribute.
7120 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr,
7121                                    Sema &S) {
7122   // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
7123   if (!(CurType->isImageType() || CurType->isPipeType())) {
7124     S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
7125     Attr.setInvalid();
7126     return;
7127   }
7128 
7129   if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
7130     QualType PointeeTy = TypedefTy->desugar();
7131     S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
7132 
7133     std::string PrevAccessQual;
7134     switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) {
7135       #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7136     case BuiltinType::Id:                                          \
7137       PrevAccessQual = #Access;                                    \
7138       break;
7139       #include "clang/Basic/OpenCLImageTypes.def"
7140     default:
7141       assert(0 && "Unable to find corresponding image type.");
7142     }
7143 
7144     S.Diag(TypedefTy->getDecl()->getLocStart(),
7145        diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
7146   } else if (CurType->isPipeType()) {
7147     if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
7148       QualType ElemType = CurType->getAs<PipeType>()->getElementType();
7149       CurType = S.Context.getWritePipeType(ElemType);
7150     }
7151   }
7152 }
7153 
7154 static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State,
7155                                           QualType &T, TypeAttrLocation TAL) {
7156   Declarator &D = State.getDeclarator();
7157 
7158   // Handle the cases where address space should not be deduced.
7159   //
7160   // The pointee type of a pointer type is always deduced since a pointer always
7161   // points to some memory location which should has an address space.
7162   //
7163   // There are situations that at the point of certain declarations, the address
7164   // space may be unknown and better to be left as default. For example, when
7165   // defining a typedef or struct type, they are not associated with any
7166   // specific address space. Later on, they may be used with any address space
7167   // to declare a variable.
7168   //
7169   // The return value of a function is r-value, therefore should not have
7170   // address space.
7171   //
7172   // The void type does not occupy memory, therefore should not have address
7173   // space, except when it is used as a pointee type.
7174   //
7175   // Since LLVM assumes function type is in default address space, it should not
7176   // have address space.
7177   auto ChunkIndex = State.getCurrentChunkIndex();
7178   bool IsPointee =
7179       ChunkIndex > 0 &&
7180       (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer ||
7181        D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer);
7182   bool IsFuncReturnType =
7183       ChunkIndex > 0 &&
7184       D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function;
7185   bool IsFuncType =
7186       ChunkIndex < D.getNumTypeObjects() &&
7187       D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function;
7188   if ( // Do not deduce addr space for function return type and function type,
7189        // otherwise it will fail some sema check.
7190       IsFuncReturnType || IsFuncType ||
7191       // Do not deduce addr space for member types of struct, except the pointee
7192       // type of a pointer member type.
7193       (D.getContext() == DeclaratorContext::MemberContext && !IsPointee) ||
7194       // Do not deduce addr space for types used to define a typedef and the
7195       // typedef itself, except the pointee type of a pointer type which is used
7196       // to define the typedef.
7197       (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef &&
7198        !IsPointee) ||
7199       // Do not deduce addr space of the void type, e.g. in f(void), otherwise
7200       // it will fail some sema check.
7201       (T->isVoidType() && !IsPointee))
7202     return;
7203 
7204   LangAS ImpAddr;
7205   // Put OpenCL automatic variable in private address space.
7206   // OpenCL v1.2 s6.5:
7207   // The default address space name for arguments to a function in a
7208   // program, or local variables of a function is __private. All function
7209   // arguments shall be in the __private address space.
7210   if (State.getSema().getLangOpts().OpenCLVersion <= 120 &&
7211       !State.getSema().getLangOpts().OpenCLCPlusPlus) {
7212     ImpAddr = LangAS::opencl_private;
7213   } else {
7214     // If address space is not set, OpenCL 2.0 defines non private default
7215     // address spaces for some cases:
7216     // OpenCL 2.0, section 6.5:
7217     // The address space for a variable at program scope or a static variable
7218     // inside a function can either be __global or __constant, but defaults to
7219     // __global if not specified.
7220     // (...)
7221     // Pointers that are declared without pointing to a named address space
7222     // point to the generic address space.
7223     if (IsPointee) {
7224       ImpAddr = LangAS::opencl_generic;
7225     } else {
7226       if (D.getContext() == DeclaratorContext::FileContext) {
7227         ImpAddr = LangAS::opencl_global;
7228       } else {
7229         if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
7230             D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) {
7231           ImpAddr = LangAS::opencl_global;
7232         } else {
7233           ImpAddr = LangAS::opencl_private;
7234         }
7235       }
7236     }
7237   }
7238   T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr);
7239 }
7240 
7241 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
7242                              TypeAttrLocation TAL, AttributeList *attrs) {
7243   // Scan through and apply attributes to this type where it makes sense.  Some
7244   // attributes (such as __address_space__, __vector_size__, etc) apply to the
7245   // type, but others can be present in the type specifiers even though they
7246   // apply to the decl.  Here we apply type attributes and ignore the rest.
7247 
7248   while (attrs) {
7249     AttributeList &attr = *attrs;
7250     attrs = attr.getNext(); // reset to the next here due to early loop continue
7251                             // stmts
7252 
7253     // Skip attributes that were marked to be invalid.
7254     if (attr.isInvalid())
7255       continue;
7256 
7257     if (attr.isCXX11Attribute()) {
7258       // [[gnu::...]] attributes are treated as declaration attributes, so may
7259       // not appertain to a DeclaratorChunk. If we handle them as type
7260       // attributes, accept them in that position and diagnose the GCC
7261       // incompatibility.
7262       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
7263         bool IsTypeAttr = attr.isTypeAttr();
7264         if (TAL == TAL_DeclChunk) {
7265           state.getSema().Diag(attr.getLoc(),
7266                                IsTypeAttr
7267                                    ? diag::warn_gcc_ignores_type_attr
7268                                    : diag::warn_cxx11_gnu_attribute_on_type)
7269               << attr.getName();
7270           if (!IsTypeAttr)
7271             continue;
7272         }
7273       } else if (TAL != TAL_DeclChunk) {
7274         // Otherwise, only consider type processing for a C++11 attribute if
7275         // it's actually been applied to a type.
7276         continue;
7277       }
7278     }
7279 
7280     // If this is an attribute we can handle, do so now,
7281     // otherwise, add it to the FnAttrs list for rechaining.
7282     switch (attr.getKind()) {
7283     default:
7284       // A C++11 attribute on a declarator chunk must appertain to a type.
7285       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
7286         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
7287           << attr.getName();
7288         attr.setUsedAsTypeAttr();
7289       }
7290       break;
7291 
7292     case AttributeList::UnknownAttribute:
7293       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
7294         state.getSema().Diag(attr.getLoc(),
7295                              diag::warn_unknown_attribute_ignored)
7296           << attr.getName();
7297       break;
7298 
7299     case AttributeList::IgnoredAttribute:
7300       break;
7301 
7302     case AttributeList::AT_MayAlias:
7303       // FIXME: This attribute needs to actually be handled, but if we ignore
7304       // it it breaks large amounts of Linux software.
7305       attr.setUsedAsTypeAttr();
7306       break;
7307     case AttributeList::AT_OpenCLPrivateAddressSpace:
7308     case AttributeList::AT_OpenCLGlobalAddressSpace:
7309     case AttributeList::AT_OpenCLLocalAddressSpace:
7310     case AttributeList::AT_OpenCLConstantAddressSpace:
7311     case AttributeList::AT_OpenCLGenericAddressSpace:
7312     case AttributeList::AT_AddressSpace:
7313       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
7314       attr.setUsedAsTypeAttr();
7315       break;
7316     OBJC_POINTER_TYPE_ATTRS_CASELIST:
7317       if (!handleObjCPointerTypeAttr(state, attr, type))
7318         distributeObjCPointerTypeAttr(state, attr, type);
7319       attr.setUsedAsTypeAttr();
7320       break;
7321     case AttributeList::AT_VectorSize:
7322       HandleVectorSizeAttr(type, attr, state.getSema());
7323       attr.setUsedAsTypeAttr();
7324       break;
7325     case AttributeList::AT_ExtVectorType:
7326       HandleExtVectorTypeAttr(type, attr, state.getSema());
7327       attr.setUsedAsTypeAttr();
7328       break;
7329     case AttributeList::AT_NeonVectorType:
7330       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7331                                VectorType::NeonVector);
7332       attr.setUsedAsTypeAttr();
7333       break;
7334     case AttributeList::AT_NeonPolyVectorType:
7335       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7336                                VectorType::NeonPolyVector);
7337       attr.setUsedAsTypeAttr();
7338       break;
7339     case AttributeList::AT_OpenCLAccess:
7340       HandleOpenCLAccessAttr(type, attr, state.getSema());
7341       attr.setUsedAsTypeAttr();
7342       break;
7343 
7344     MS_TYPE_ATTRS_CASELIST:
7345       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
7346         attr.setUsedAsTypeAttr();
7347       break;
7348 
7349 
7350     NULLABILITY_TYPE_ATTRS_CASELIST:
7351       // Either add nullability here or try to distribute it.  We
7352       // don't want to distribute the nullability specifier past any
7353       // dependent type, because that complicates the user model.
7354       if (type->canHaveNullability() || type->isDependentType() ||
7355           type->isArrayType() ||
7356           !distributeNullabilityTypeAttr(state, type, attr)) {
7357         unsigned endIndex;
7358         if (TAL == TAL_DeclChunk)
7359           endIndex = state.getCurrentChunkIndex();
7360         else
7361           endIndex = state.getDeclarator().getNumTypeObjects();
7362         bool allowOnArrayType =
7363             state.getDeclarator().isPrototypeContext() &&
7364             !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
7365         if (state.getSema().checkNullabilityTypeSpecifier(
7366               type,
7367               mapNullabilityAttrKind(attr.getKind()),
7368               attr.getLoc(),
7369               attr.isContextSensitiveKeywordAttribute(),
7370               allowOnArrayType)) {
7371           attr.setInvalid();
7372         }
7373 
7374         attr.setUsedAsTypeAttr();
7375       }
7376       break;
7377 
7378     case AttributeList::AT_ObjCKindOf:
7379       // '__kindof' must be part of the decl-specifiers.
7380       switch (TAL) {
7381       case TAL_DeclSpec:
7382         break;
7383 
7384       case TAL_DeclChunk:
7385       case TAL_DeclName:
7386         state.getSema().Diag(attr.getLoc(),
7387                              diag::err_objc_kindof_wrong_position)
7388           << FixItHint::CreateRemoval(attr.getLoc())
7389           << FixItHint::CreateInsertion(
7390                state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
7391         break;
7392       }
7393 
7394       // Apply it regardless.
7395       if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
7396         attr.setInvalid();
7397       attr.setUsedAsTypeAttr();
7398       break;
7399 
7400     FUNCTION_TYPE_ATTRS_CASELIST:
7401       attr.setUsedAsTypeAttr();
7402 
7403       // Never process function type attributes as part of the
7404       // declaration-specifiers.
7405       if (TAL == TAL_DeclSpec)
7406         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
7407 
7408       // Otherwise, handle the possible delays.
7409       else if (!handleFunctionTypeAttr(state, attr, type))
7410         distributeFunctionTypeAttr(state, attr, type);
7411       break;
7412     }
7413   }
7414 
7415   if (!state.getSema().getLangOpts().OpenCL ||
7416       type.getAddressSpace() != LangAS::Default)
7417     return;
7418 
7419   deduceOpenCLImplicitAddrSpace(state, type, TAL);
7420 }
7421 
7422 void Sema::completeExprArrayBound(Expr *E) {
7423   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7424     if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7425       if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
7426         auto *Def = Var->getDefinition();
7427         if (!Def) {
7428           SourceLocation PointOfInstantiation = E->getExprLoc();
7429           InstantiateVariableDefinition(PointOfInstantiation, Var);
7430           Def = Var->getDefinition();
7431 
7432           // If we don't already have a point of instantiation, and we managed
7433           // to instantiate a definition, this is the point of instantiation.
7434           // Otherwise, we don't request an end-of-TU instantiation, so this is
7435           // not a point of instantiation.
7436           // FIXME: Is this really the right behavior?
7437           if (Var->getPointOfInstantiation().isInvalid() && Def) {
7438             assert(Var->getTemplateSpecializationKind() ==
7439                        TSK_ImplicitInstantiation &&
7440                    "explicit instantiation with no point of instantiation");
7441             Var->setTemplateSpecializationKind(
7442                 Var->getTemplateSpecializationKind(), PointOfInstantiation);
7443           }
7444         }
7445 
7446         // Update the type to the definition's type both here and within the
7447         // expression.
7448         if (Def) {
7449           DRE->setDecl(Def);
7450           QualType T = Def->getType();
7451           DRE->setType(T);
7452           // FIXME: Update the type on all intervening expressions.
7453           E->setType(T);
7454         }
7455 
7456         // We still go on to try to complete the type independently, as it
7457         // may also require instantiations or diagnostics if it remains
7458         // incomplete.
7459       }
7460     }
7461   }
7462 }
7463 
7464 /// Ensure that the type of the given expression is complete.
7465 ///
7466 /// This routine checks whether the expression \p E has a complete type. If the
7467 /// expression refers to an instantiable construct, that instantiation is
7468 /// performed as needed to complete its type. Furthermore
7469 /// Sema::RequireCompleteType is called for the expression's type (or in the
7470 /// case of a reference type, the referred-to type).
7471 ///
7472 /// \param E The expression whose type is required to be complete.
7473 /// \param Diagnoser The object that will emit a diagnostic if the type is
7474 /// incomplete.
7475 ///
7476 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
7477 /// otherwise.
7478 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
7479   QualType T = E->getType();
7480 
7481   // Incomplete array types may be completed by the initializer attached to
7482   // their definitions. For static data members of class templates and for
7483   // variable templates, we need to instantiate the definition to get this
7484   // initializer and complete the type.
7485   if (T->isIncompleteArrayType()) {
7486     completeExprArrayBound(E);
7487     T = E->getType();
7488   }
7489 
7490   // FIXME: Are there other cases which require instantiating something other
7491   // than the type to complete the type of an expression?
7492 
7493   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
7494 }
7495 
7496 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
7497   BoundTypeDiagnoser<> Diagnoser(DiagID);
7498   return RequireCompleteExprType(E, Diagnoser);
7499 }
7500 
7501 /// Ensure that the type T is a complete type.
7502 ///
7503 /// This routine checks whether the type @p T is complete in any
7504 /// context where a complete type is required. If @p T is a complete
7505 /// type, returns false. If @p T is a class template specialization,
7506 /// this routine then attempts to perform class template
7507 /// instantiation. If instantiation fails, or if @p T is incomplete
7508 /// and cannot be completed, issues the diagnostic @p diag (giving it
7509 /// the type @p T) and returns true.
7510 ///
7511 /// @param Loc  The location in the source that the incomplete type
7512 /// diagnostic should refer to.
7513 ///
7514 /// @param T  The type that this routine is examining for completeness.
7515 ///
7516 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7517 /// @c false otherwise.
7518 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7519                                TypeDiagnoser &Diagnoser) {
7520   if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7521     return true;
7522   if (const TagType *Tag = T->getAs<TagType>()) {
7523     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7524       Tag->getDecl()->setCompleteDefinitionRequired();
7525       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7526     }
7527   }
7528   return false;
7529 }
7530 
7531 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
7532   llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
7533   if (!Suggested)
7534     return false;
7535 
7536   // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
7537   // and isolate from other C++ specific checks.
7538   StructuralEquivalenceContext Ctx(
7539       D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
7540       false /*StrictTypeSpelling*/, true /*Complain*/,
7541       true /*ErrorOnTagTypeMismatch*/);
7542   return Ctx.IsStructurallyEquivalent(D, Suggested);
7543 }
7544 
7545 /// Determine whether there is any declaration of \p D that was ever a
7546 ///        definition (perhaps before module merging) and is currently visible.
7547 /// \param D The definition of the entity.
7548 /// \param Suggested Filled in with the declaration that should be made visible
7549 ///        in order to provide a definition of this entity.
7550 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7551 ///        not defined. This only matters for enums with a fixed underlying
7552 ///        type, since in all other cases, a type is complete if and only if it
7553 ///        is defined.
7554 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
7555                                 bool OnlyNeedComplete) {
7556   // Easy case: if we don't have modules, all declarations are visible.
7557   if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7558     return true;
7559 
7560   // If this definition was instantiated from a template, map back to the
7561   // pattern from which it was instantiated.
7562   if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7563     // We're in the middle of defining it; this definition should be treated
7564     // as visible.
7565     return true;
7566   } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7567     if (auto *Pattern = RD->getTemplateInstantiationPattern())
7568       RD = Pattern;
7569     D = RD->getDefinition();
7570   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7571     if (auto *Pattern = ED->getTemplateInstantiationPattern())
7572       ED = Pattern;
7573     if (OnlyNeedComplete && ED->isFixed()) {
7574       // If the enum has a fixed underlying type, and we're only looking for a
7575       // complete type (not a definition), any visible declaration of it will
7576       // do.
7577       *Suggested = nullptr;
7578       for (auto *Redecl : ED->redecls()) {
7579         if (isVisible(Redecl))
7580           return true;
7581         if (Redecl->isThisDeclarationADefinition() ||
7582             (Redecl->isCanonicalDecl() && !*Suggested))
7583           *Suggested = Redecl;
7584       }
7585       return false;
7586     }
7587     D = ED->getDefinition();
7588   } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7589     if (auto *Pattern = FD->getTemplateInstantiationPattern())
7590       FD = Pattern;
7591     D = FD->getDefinition();
7592   } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7593     if (auto *Pattern = VD->getTemplateInstantiationPattern())
7594       VD = Pattern;
7595     D = VD->getDefinition();
7596   }
7597   assert(D && "missing definition for pattern of instantiated definition");
7598 
7599   *Suggested = D;
7600   if (isVisible(D))
7601     return true;
7602 
7603   // The external source may have additional definitions of this entity that are
7604   // visible, so complete the redeclaration chain now and ask again.
7605   if (auto *Source = Context.getExternalSource()) {
7606     Source->CompleteRedeclChain(D);
7607     return isVisible(D);
7608   }
7609 
7610   return false;
7611 }
7612 
7613 /// Locks in the inheritance model for the given class and all of its bases.
7614 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
7615   RD = RD->getMostRecentNonInjectedDecl();
7616   if (!RD->hasAttr<MSInheritanceAttr>()) {
7617     MSInheritanceAttr::Spelling IM;
7618 
7619     switch (S.MSPointerToMemberRepresentationMethod) {
7620     case LangOptions::PPTMK_BestCase:
7621       IM = RD->calculateInheritanceModel();
7622       break;
7623     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
7624       IM = MSInheritanceAttr::Keyword_single_inheritance;
7625       break;
7626     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
7627       IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7628       break;
7629     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
7630       IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7631       break;
7632     }
7633 
7634     RD->addAttr(MSInheritanceAttr::CreateImplicit(
7635         S.getASTContext(), IM,
7636         /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7637             LangOptions::PPTMK_BestCase,
7638         S.ImplicitMSInheritanceAttrLoc.isValid()
7639             ? S.ImplicitMSInheritanceAttrLoc
7640             : RD->getSourceRange()));
7641     S.Consumer.AssignInheritanceModel(RD);
7642   }
7643 }
7644 
7645 /// The implementation of RequireCompleteType
7646 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7647                                    TypeDiagnoser *Diagnoser) {
7648   // FIXME: Add this assertion to make sure we always get instantiation points.
7649   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7650   // FIXME: Add this assertion to help us flush out problems with
7651   // checking for dependent types and type-dependent expressions.
7652   //
7653   //  assert(!T->isDependentType() &&
7654   //         "Can't ask whether a dependent type is complete");
7655 
7656   if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7657     if (!MPTy->getClass()->isDependentType()) {
7658       if (getLangOpts().CompleteMemberPointers &&
7659           !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
7660           RequireCompleteType(Loc, QualType(MPTy->getClass(), 0),
7661                               diag::err_memptr_incomplete))
7662         return true;
7663 
7664       // We lock in the inheritance model once somebody has asked us to ensure
7665       // that a pointer-to-member type is complete.
7666       if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7667         (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7668         assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7669       }
7670     }
7671   }
7672 
7673   NamedDecl *Def = nullptr;
7674   bool Incomplete = T->isIncompleteType(&Def);
7675 
7676   // Check that any necessary explicit specializations are visible. For an
7677   // enum, we just need the declaration, so don't check this.
7678   if (Def && !isa<EnumDecl>(Def))
7679     checkSpecializationVisibility(Loc, Def);
7680 
7681   // If we have a complete type, we're done.
7682   if (!Incomplete) {
7683     // If we know about the definition but it is not visible, complain.
7684     NamedDecl *SuggestedDef = nullptr;
7685     if (Def &&
7686         !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7687       // If the user is going to see an error here, recover by making the
7688       // definition visible.
7689       bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7690       if (Diagnoser && SuggestedDef)
7691         diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7692                               /*Recover*/TreatAsComplete);
7693       return !TreatAsComplete;
7694     } else if (Def && !TemplateInstCallbacks.empty()) {
7695       CodeSynthesisContext TempInst;
7696       TempInst.Kind = CodeSynthesisContext::Memoization;
7697       TempInst.Template = Def;
7698       TempInst.Entity = Def;
7699       TempInst.PointOfInstantiation = Loc;
7700       atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
7701       atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
7702     }
7703 
7704     return false;
7705   }
7706 
7707   const TagType *Tag = T->getAs<TagType>();
7708   const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
7709 
7710   // If there's an unimported definition of this type in a module (for
7711   // instance, because we forward declared it, then imported the definition),
7712   // import that definition now.
7713   //
7714   // FIXME: What about other cases where an import extends a redeclaration
7715   // chain for a declaration that can be accessed through a mechanism other
7716   // than name lookup (eg, referenced in a template, or a variable whose type
7717   // could be completed by the module)?
7718   //
7719   // FIXME: Should we map through to the base array element type before
7720   // checking for a tag type?
7721   if (Tag || IFace) {
7722     NamedDecl *D =
7723         Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
7724 
7725     // Avoid diagnosing invalid decls as incomplete.
7726     if (D->isInvalidDecl())
7727       return true;
7728 
7729     // Give the external AST source a chance to complete the type.
7730     if (auto *Source = Context.getExternalSource()) {
7731       if (Tag) {
7732         TagDecl *TagD = Tag->getDecl();
7733         if (TagD->hasExternalLexicalStorage())
7734           Source->CompleteType(TagD);
7735       } else {
7736         ObjCInterfaceDecl *IFaceD = IFace->getDecl();
7737         if (IFaceD->hasExternalLexicalStorage())
7738           Source->CompleteType(IFace->getDecl());
7739       }
7740       // If the external source completed the type, go through the motions
7741       // again to ensure we're allowed to use the completed type.
7742       if (!T->isIncompleteType())
7743         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7744     }
7745   }
7746 
7747   // If we have a class template specialization or a class member of a
7748   // class template specialization, or an array with known size of such,
7749   // try to instantiate it.
7750   QualType MaybeTemplate = T;
7751   while (const ConstantArrayType *Array
7752            = Context.getAsConstantArrayType(MaybeTemplate))
7753     MaybeTemplate = Array->getElementType();
7754   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
7755     bool Instantiated = false;
7756     bool Diagnosed = false;
7757     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
7758           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
7759       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7760         Diagnosed = InstantiateClassTemplateSpecialization(
7761             Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7762             /*Complain=*/Diagnoser);
7763         Instantiated = true;
7764       }
7765     } else if (CXXRecordDecl *Rec
7766                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
7767       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
7768       if (!Rec->isBeingDefined() && Pattern) {
7769         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
7770         assert(MSI && "Missing member specialization information?");
7771         // This record was instantiated from a class within a template.
7772         if (MSI->getTemplateSpecializationKind() !=
7773             TSK_ExplicitSpecialization) {
7774           Diagnosed = InstantiateClass(Loc, Rec, Pattern,
7775                                        getTemplateInstantiationArgs(Rec),
7776                                        TSK_ImplicitInstantiation,
7777                                        /*Complain=*/Diagnoser);
7778           Instantiated = true;
7779         }
7780       }
7781     }
7782 
7783     if (Instantiated) {
7784       // Instantiate* might have already complained that the template is not
7785       // defined, if we asked it to.
7786       if (Diagnoser && Diagnosed)
7787         return true;
7788       // If we instantiated a definition, check that it's usable, even if
7789       // instantiation produced an error, so that repeated calls to this
7790       // function give consistent answers.
7791       if (!T->isIncompleteType())
7792         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7793     }
7794   }
7795 
7796   // FIXME: If we didn't instantiate a definition because of an explicit
7797   // specialization declaration, check that it's visible.
7798 
7799   if (!Diagnoser)
7800     return true;
7801 
7802   Diagnoser->diagnose(*this, Loc, T);
7803 
7804   // If the type was a forward declaration of a class/struct/union
7805   // type, produce a note.
7806   if (Tag && !Tag->getDecl()->isInvalidDecl())
7807     Diag(Tag->getDecl()->getLocation(),
7808          Tag->isBeingDefined() ? diag::note_type_being_defined
7809                                : diag::note_forward_declaration)
7810       << QualType(Tag, 0);
7811 
7812   // If the Objective-C class was a forward declaration, produce a note.
7813   if (IFace && !IFace->getDecl()->isInvalidDecl())
7814     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7815 
7816   // If we have external information that we can use to suggest a fix,
7817   // produce a note.
7818   if (ExternalSource)
7819     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7820 
7821   return true;
7822 }
7823 
7824 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7825                                unsigned DiagID) {
7826   BoundTypeDiagnoser<> Diagnoser(DiagID);
7827   return RequireCompleteType(Loc, T, Diagnoser);
7828 }
7829 
7830 /// Get diagnostic %select index for tag kind for
7831 /// literal type diagnostic message.
7832 /// WARNING: Indexes apply to particular diagnostics only!
7833 ///
7834 /// \returns diagnostic %select index.
7835 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7836   switch (Tag) {
7837   case TTK_Struct: return 0;
7838   case TTK_Interface: return 1;
7839   case TTK_Class:  return 2;
7840   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7841   }
7842 }
7843 
7844 /// Ensure that the type T is a literal type.
7845 ///
7846 /// This routine checks whether the type @p T is a literal type. If @p T is an
7847 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7848 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7849 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7850 /// it the type @p T), along with notes explaining why the type is not a
7851 /// literal type, and returns true.
7852 ///
7853 /// @param Loc  The location in the source that the non-literal type
7854 /// diagnostic should refer to.
7855 ///
7856 /// @param T  The type that this routine is examining for literalness.
7857 ///
7858 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7859 ///
7860 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7861 /// @c false otherwise.
7862 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7863                               TypeDiagnoser &Diagnoser) {
7864   assert(!T->isDependentType() && "type should not be dependent");
7865 
7866   QualType ElemType = Context.getBaseElementType(T);
7867   if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7868       T->isLiteralType(Context))
7869     return false;
7870 
7871   Diagnoser.diagnose(*this, Loc, T);
7872 
7873   if (T->isVariableArrayType())
7874     return true;
7875 
7876   const RecordType *RT = ElemType->getAs<RecordType>();
7877   if (!RT)
7878     return true;
7879 
7880   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7881 
7882   // A partially-defined class type can't be a literal type, because a literal
7883   // class type must have a trivial destructor (which can't be checked until
7884   // the class definition is complete).
7885   if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7886     return true;
7887 
7888   // [expr.prim.lambda]p3:
7889   //   This class type is [not] a literal type.
7890   if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
7891     Diag(RD->getLocation(), diag::note_non_literal_lambda);
7892     return true;
7893   }
7894 
7895   // If the class has virtual base classes, then it's not an aggregate, and
7896   // cannot have any constexpr constructors or a trivial default constructor,
7897   // so is non-literal. This is better to diagnose than the resulting absence
7898   // of constexpr constructors.
7899   if (RD->getNumVBases()) {
7900     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7901       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7902     for (const auto &I : RD->vbases())
7903       Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7904           << I.getSourceRange();
7905   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7906              !RD->hasTrivialDefaultConstructor()) {
7907     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7908   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7909     for (const auto &I : RD->bases()) {
7910       if (!I.getType()->isLiteralType(Context)) {
7911         Diag(I.getLocStart(),
7912              diag::note_non_literal_base_class)
7913           << RD << I.getType() << I.getSourceRange();
7914         return true;
7915       }
7916     }
7917     for (const auto *I : RD->fields()) {
7918       if (!I->getType()->isLiteralType(Context) ||
7919           I->getType().isVolatileQualified()) {
7920         Diag(I->getLocation(), diag::note_non_literal_field)
7921           << RD << I << I->getType()
7922           << I->getType().isVolatileQualified();
7923         return true;
7924       }
7925     }
7926   } else if (!RD->hasTrivialDestructor()) {
7927     // All fields and bases are of literal types, so have trivial destructors.
7928     // If this class's destructor is non-trivial it must be user-declared.
7929     CXXDestructorDecl *Dtor = RD->getDestructor();
7930     assert(Dtor && "class has literal fields and bases but no dtor?");
7931     if (!Dtor)
7932       return true;
7933 
7934     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7935          diag::note_non_literal_user_provided_dtor :
7936          diag::note_non_literal_nontrivial_dtor) << RD;
7937     if (!Dtor->isUserProvided())
7938       SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
7939                              /*Diagnose*/true);
7940   }
7941 
7942   return true;
7943 }
7944 
7945 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7946   BoundTypeDiagnoser<> Diagnoser(DiagID);
7947   return RequireLiteralType(Loc, T, Diagnoser);
7948 }
7949 
7950 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
7951 /// by the nested-name-specifier contained in SS, and that is (re)declared by
7952 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
7953 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7954                                  const CXXScopeSpec &SS, QualType T,
7955                                  TagDecl *OwnedTagDecl) {
7956   if (T.isNull())
7957     return T;
7958   NestedNameSpecifier *NNS;
7959   if (SS.isValid())
7960     NNS = SS.getScopeRep();
7961   else {
7962     if (Keyword == ETK_None)
7963       return T;
7964     NNS = nullptr;
7965   }
7966   return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl);
7967 }
7968 
7969 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7970   ExprResult ER = CheckPlaceholderExpr(E);
7971   if (ER.isInvalid()) return QualType();
7972   E = ER.get();
7973 
7974   if (!getLangOpts().CPlusPlus && E->refersToBitField())
7975     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7976 
7977   if (!E->isTypeDependent()) {
7978     QualType T = E->getType();
7979     if (const TagType *TT = T->getAs<TagType>())
7980       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7981   }
7982   return Context.getTypeOfExprType(E);
7983 }
7984 
7985 /// getDecltypeForExpr - Given an expr, will return the decltype for
7986 /// that expression, according to the rules in C++11
7987 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
7988 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7989   if (E->isTypeDependent())
7990     return S.Context.DependentTy;
7991 
7992   // C++11 [dcl.type.simple]p4:
7993   //   The type denoted by decltype(e) is defined as follows:
7994   //
7995   //     - if e is an unparenthesized id-expression or an unparenthesized class
7996   //       member access (5.2.5), decltype(e) is the type of the entity named
7997   //       by e. If there is no such entity, or if e names a set of overloaded
7998   //       functions, the program is ill-formed;
7999   //
8000   // We apply the same rules for Objective-C ivar and property references.
8001   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8002     const ValueDecl *VD = DRE->getDecl();
8003     return VD->getType();
8004   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8005     if (const ValueDecl *VD = ME->getMemberDecl())
8006       if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
8007         return VD->getType();
8008   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
8009     return IR->getDecl()->getType();
8010   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
8011     if (PR->isExplicitProperty())
8012       return PR->getExplicitProperty()->getType();
8013   } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
8014     return PE->getType();
8015   }
8016 
8017   // C++11 [expr.lambda.prim]p18:
8018   //   Every occurrence of decltype((x)) where x is a possibly
8019   //   parenthesized id-expression that names an entity of automatic
8020   //   storage duration is treated as if x were transformed into an
8021   //   access to a corresponding data member of the closure type that
8022   //   would have been declared if x were an odr-use of the denoted
8023   //   entity.
8024   using namespace sema;
8025   if (S.getCurLambda()) {
8026     if (isa<ParenExpr>(E)) {
8027       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8028         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8029           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
8030           if (!T.isNull())
8031             return S.Context.getLValueReferenceType(T);
8032         }
8033       }
8034     }
8035   }
8036 
8037 
8038   // C++11 [dcl.type.simple]p4:
8039   //   [...]
8040   QualType T = E->getType();
8041   switch (E->getValueKind()) {
8042   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
8043   //       type of e;
8044   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
8045   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
8046   //       type of e;
8047   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
8048   //  - otherwise, decltype(e) is the type of e.
8049   case VK_RValue: break;
8050   }
8051 
8052   return T;
8053 }
8054 
8055 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
8056                                  bool AsUnevaluated) {
8057   ExprResult ER = CheckPlaceholderExpr(E);
8058   if (ER.isInvalid()) return QualType();
8059   E = ER.get();
8060 
8061   if (AsUnevaluated && CodeSynthesisContexts.empty() &&
8062       E->HasSideEffects(Context, false)) {
8063     // The expression operand for decltype is in an unevaluated expression
8064     // context, so side effects could result in unintended consequences.
8065     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8066   }
8067 
8068   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
8069 }
8070 
8071 QualType Sema::BuildUnaryTransformType(QualType BaseType,
8072                                        UnaryTransformType::UTTKind UKind,
8073                                        SourceLocation Loc) {
8074   switch (UKind) {
8075   case UnaryTransformType::EnumUnderlyingType:
8076     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
8077       Diag(Loc, diag::err_only_enums_have_underlying_types);
8078       return QualType();
8079     } else {
8080       QualType Underlying = BaseType;
8081       if (!BaseType->isDependentType()) {
8082         // The enum could be incomplete if we're parsing its definition or
8083         // recovering from an error.
8084         NamedDecl *FwdDecl = nullptr;
8085         if (BaseType->isIncompleteType(&FwdDecl)) {
8086           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
8087           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
8088           return QualType();
8089         }
8090 
8091         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
8092         assert(ED && "EnumType has no EnumDecl");
8093 
8094         DiagnoseUseOfDecl(ED, Loc);
8095 
8096         Underlying = ED->getIntegerType();
8097         assert(!Underlying.isNull());
8098       }
8099       return Context.getUnaryTransformType(BaseType, Underlying,
8100                                         UnaryTransformType::EnumUnderlyingType);
8101     }
8102   }
8103   llvm_unreachable("unknown unary transform type");
8104 }
8105 
8106 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
8107   if (!T->isDependentType()) {
8108     // FIXME: It isn't entirely clear whether incomplete atomic types
8109     // are allowed or not; for simplicity, ban them for the moment.
8110     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
8111       return QualType();
8112 
8113     int DisallowedKind = -1;
8114     if (T->isArrayType())
8115       DisallowedKind = 1;
8116     else if (T->isFunctionType())
8117       DisallowedKind = 2;
8118     else if (T->isReferenceType())
8119       DisallowedKind = 3;
8120     else if (T->isAtomicType())
8121       DisallowedKind = 4;
8122     else if (T.hasQualifiers())
8123       DisallowedKind = 5;
8124     else if (!T.isTriviallyCopyableType(Context))
8125       // Some other non-trivially-copyable type (probably a C++ class)
8126       DisallowedKind = 6;
8127 
8128     if (DisallowedKind != -1) {
8129       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
8130       return QualType();
8131     }
8132 
8133     // FIXME: Do we need any handling for ARC here?
8134   }
8135 
8136   // Build the pointer type.
8137   return Context.getAtomicType(T);
8138 }
8139