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