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.
2739     T = SemaRef.Context.getAutoDeductType();
2740     if (!D.hasTrailingReturnType()) {
2741       SemaRef.Diag(D.getName().getLocStart(),
2742                    diag::err_deduction_guide_no_trailing_return_type);
2743       D.setInvalidType(true);
2744     }
2745     break;
2746 
2747   case UnqualifiedId::IK_ConversionFunctionId:
2748     // The result type of a conversion function is the type that it
2749     // converts to.
2750     T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2751                                   &ReturnTypeInfo);
2752     break;
2753   }
2754 
2755   if (D.getAttributes())
2756     distributeTypeAttrsFromDeclarator(state, T);
2757 
2758   // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2759   if (DeducedType *Deduced = T->getContainedDeducedType()) {
2760     AutoType *Auto = dyn_cast<AutoType>(Deduced);
2761     int Error = -1;
2762 
2763     // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2764     // class template argument deduction)?
2765     bool IsCXXAutoType =
2766         (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2767 
2768     switch (D.getContext()) {
2769     case Declarator::LambdaExprContext:
2770       // Declared return type of a lambda-declarator is implicit and is always
2771       // 'auto'.
2772       break;
2773     case Declarator::ObjCParameterContext:
2774     case Declarator::ObjCResultContext:
2775     case Declarator::PrototypeContext:
2776       Error = 0;
2777       break;
2778     case Declarator::LambdaExprParameterContext:
2779       // In C++14, generic lambdas allow 'auto' in their parameters.
2780       if (!SemaRef.getLangOpts().CPlusPlus14 ||
2781           !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2782         Error = 16;
2783       else {
2784         // If auto is mentioned in a lambda parameter context, convert it to a
2785         // template parameter type.
2786         sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2787         assert(LSI && "No LambdaScopeInfo on the stack!");
2788         const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2789         const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
2790         const bool IsParameterPack = D.hasEllipsis();
2791 
2792         // Create the TemplateTypeParmDecl here to retrieve the corresponding
2793         // template parameter type. Template parameters are temporarily added
2794         // to the TU until the associated TemplateDecl is created.
2795         TemplateTypeParmDecl *CorrespondingTemplateParam =
2796             TemplateTypeParmDecl::Create(
2797                 SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2798                 /*KeyLoc*/SourceLocation(), /*NameLoc*/D.getLocStart(),
2799                 TemplateParameterDepth, AutoParameterPosition,
2800                 /*Identifier*/nullptr, false, IsParameterPack);
2801         LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
2802         // Replace the 'auto' in the function parameter with this invented
2803         // template type parameter.
2804         // FIXME: Retain some type sugar to indicate that this was written
2805         // as 'auto'.
2806         T = SemaRef.ReplaceAutoType(
2807             T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2808       }
2809       break;
2810     case Declarator::MemberContext: {
2811       if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2812           D.isFunctionDeclarator())
2813         break;
2814       bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2815       switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2816       case TTK_Enum: llvm_unreachable("unhandled tag kind");
2817       case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2818       case TTK_Union:  Error = Cxx ? 3 : 4; /* Union member */ break;
2819       case TTK_Class:  Error = 5; /* Class member */ break;
2820       case TTK_Interface: Error = 6; /* Interface member */ break;
2821       }
2822       if (D.getDeclSpec().isFriendSpecified())
2823         Error = 20; // Friend type
2824       break;
2825     }
2826     case Declarator::CXXCatchContext:
2827     case Declarator::ObjCCatchContext:
2828       Error = 7; // Exception declaration
2829       break;
2830     case Declarator::TemplateParamContext:
2831       if (isa<DeducedTemplateSpecializationType>(Deduced))
2832         Error = 19; // Template parameter
2833       else if (!SemaRef.getLangOpts().CPlusPlus1z)
2834         Error = 8; // Template parameter (until C++1z)
2835       break;
2836     case Declarator::BlockLiteralContext:
2837       Error = 9; // Block literal
2838       break;
2839     case Declarator::TemplateTypeArgContext:
2840       Error = 10; // Template type argument
2841       break;
2842     case Declarator::AliasDeclContext:
2843     case Declarator::AliasTemplateContext:
2844       Error = 12; // Type alias
2845       break;
2846     case Declarator::TrailingReturnContext:
2847       if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2848         Error = 13; // Function return type
2849       break;
2850     case Declarator::ConversionIdContext:
2851       if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2852         Error = 14; // conversion-type-id
2853       break;
2854     case Declarator::FunctionalCastContext:
2855       if (isa<DeducedTemplateSpecializationType>(Deduced))
2856         break;
2857       LLVM_FALLTHROUGH;
2858     case Declarator::TypeNameContext:
2859       Error = 15; // Generic
2860       break;
2861     case Declarator::FileContext:
2862     case Declarator::BlockContext:
2863     case Declarator::ForContext:
2864     case Declarator::InitStmtContext:
2865     case Declarator::ConditionContext:
2866       // FIXME: P0091R3 (erroneously) does not permit class template argument
2867       // deduction in conditions, for-init-statements, and other declarations
2868       // that are not simple-declarations.
2869       break;
2870     case Declarator::CXXNewContext:
2871       // FIXME: P0091R3 does not permit class template argument deduction here,
2872       // but we follow GCC and allow it anyway.
2873       if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
2874         Error = 17; // 'new' type
2875       break;
2876     case Declarator::KNRTypeListContext:
2877       Error = 18; // K&R function parameter
2878       break;
2879     }
2880 
2881     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2882       Error = 11;
2883 
2884     // In Objective-C it is an error to use 'auto' on a function declarator
2885     // (and everywhere for '__auto_type').
2886     if (D.isFunctionDeclarator() &&
2887         (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
2888       Error = 13;
2889 
2890     bool HaveTrailing = false;
2891 
2892     // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2893     // contains a trailing return type. That is only legal at the outermost
2894     // level. Check all declarator chunks (outermost first) anyway, to give
2895     // better diagnostics.
2896     // We don't support '__auto_type' with trailing return types.
2897     // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
2898     if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
2899         D.hasTrailingReturnType()) {
2900       HaveTrailing = true;
2901       Error = -1;
2902     }
2903 
2904     SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2905     if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2906       AutoRange = D.getName().getSourceRange();
2907 
2908     if (Error != -1) {
2909       unsigned Kind;
2910       if (Auto) {
2911         switch (Auto->getKeyword()) {
2912         case AutoTypeKeyword::Auto: Kind = 0; break;
2913         case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
2914         case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
2915         }
2916       } else {
2917         assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
2918                "unknown auto type");
2919         Kind = 3;
2920       }
2921 
2922       auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
2923       TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
2924 
2925       SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2926         << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
2927         << QualType(Deduced, 0) << AutoRange;
2928       if (auto *TD = TN.getAsTemplateDecl())
2929         SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
2930 
2931       T = SemaRef.Context.IntTy;
2932       D.setInvalidType(true);
2933     } else if (!HaveTrailing) {
2934       // If there was a trailing return type, we already got
2935       // warn_cxx98_compat_trailing_return_type in the parser.
2936       SemaRef.Diag(AutoRange.getBegin(),
2937                    diag::warn_cxx98_compat_auto_type_specifier)
2938         << AutoRange;
2939     }
2940   }
2941 
2942   if (SemaRef.getLangOpts().CPlusPlus &&
2943       OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2944     // Check the contexts where C++ forbids the declaration of a new class
2945     // or enumeration in a type-specifier-seq.
2946     unsigned DiagID = 0;
2947     switch (D.getContext()) {
2948     case Declarator::TrailingReturnContext:
2949       // Class and enumeration definitions are syntactically not allowed in
2950       // trailing return types.
2951       llvm_unreachable("parser should not have allowed this");
2952       break;
2953     case Declarator::FileContext:
2954     case Declarator::MemberContext:
2955     case Declarator::BlockContext:
2956     case Declarator::ForContext:
2957     case Declarator::InitStmtContext:
2958     case Declarator::BlockLiteralContext:
2959     case Declarator::LambdaExprContext:
2960       // C++11 [dcl.type]p3:
2961       //   A type-specifier-seq shall not define a class or enumeration unless
2962       //   it appears in the type-id of an alias-declaration (7.1.3) that is not
2963       //   the declaration of a template-declaration.
2964     case Declarator::AliasDeclContext:
2965       break;
2966     case Declarator::AliasTemplateContext:
2967       DiagID = diag::err_type_defined_in_alias_template;
2968       break;
2969     case Declarator::TypeNameContext:
2970     case Declarator::FunctionalCastContext:
2971     case Declarator::ConversionIdContext:
2972     case Declarator::TemplateParamContext:
2973     case Declarator::CXXNewContext:
2974     case Declarator::CXXCatchContext:
2975     case Declarator::ObjCCatchContext:
2976     case Declarator::TemplateTypeArgContext:
2977       DiagID = diag::err_type_defined_in_type_specifier;
2978       break;
2979     case Declarator::PrototypeContext:
2980     case Declarator::LambdaExprParameterContext:
2981     case Declarator::ObjCParameterContext:
2982     case Declarator::ObjCResultContext:
2983     case Declarator::KNRTypeListContext:
2984       // C++ [dcl.fct]p6:
2985       //   Types shall not be defined in return or parameter types.
2986       DiagID = diag::err_type_defined_in_param_type;
2987       break;
2988     case Declarator::ConditionContext:
2989       // C++ 6.4p2:
2990       // The type-specifier-seq shall not contain typedef and shall not declare
2991       // a new class or enumeration.
2992       DiagID = diag::err_type_defined_in_condition;
2993       break;
2994     }
2995 
2996     if (DiagID != 0) {
2997       SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
2998           << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2999       D.setInvalidType(true);
3000     }
3001   }
3002 
3003   assert(!T.isNull() && "This function should not return a null type");
3004   return T;
3005 }
3006 
3007 /// Produce an appropriate diagnostic for an ambiguity between a function
3008 /// declarator and a C++ direct-initializer.
3009 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3010                                        DeclaratorChunk &DeclType, QualType RT) {
3011   const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3012   assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3013 
3014   // If the return type is void there is no ambiguity.
3015   if (RT->isVoidType())
3016     return;
3017 
3018   // An initializer for a non-class type can have at most one argument.
3019   if (!RT->isRecordType() && FTI.NumParams > 1)
3020     return;
3021 
3022   // An initializer for a reference must have exactly one argument.
3023   if (RT->isReferenceType() && FTI.NumParams != 1)
3024     return;
3025 
3026   // Only warn if this declarator is declaring a function at block scope, and
3027   // doesn't have a storage class (such as 'extern') specified.
3028   if (!D.isFunctionDeclarator() ||
3029       D.getFunctionDefinitionKind() != FDK_Declaration ||
3030       !S.CurContext->isFunctionOrMethod() ||
3031       D.getDeclSpec().getStorageClassSpec()
3032         != DeclSpec::SCS_unspecified)
3033     return;
3034 
3035   // Inside a condition, a direct initializer is not permitted. We allow one to
3036   // be parsed in order to give better diagnostics in condition parsing.
3037   if (D.getContext() == Declarator::ConditionContext)
3038     return;
3039 
3040   SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3041 
3042   S.Diag(DeclType.Loc,
3043          FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3044                        : diag::warn_empty_parens_are_function_decl)
3045       << ParenRange;
3046 
3047   // If the declaration looks like:
3048   //   T var1,
3049   //   f();
3050   // and name lookup finds a function named 'f', then the ',' was
3051   // probably intended to be a ';'.
3052   if (!D.isFirstDeclarator() && D.getIdentifier()) {
3053     FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3054     FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3055     if (Comma.getFileID() != Name.getFileID() ||
3056         Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3057       LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3058                           Sema::LookupOrdinaryName);
3059       if (S.LookupName(Result, S.getCurScope()))
3060         S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3061           << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3062           << D.getIdentifier();
3063     }
3064   }
3065 
3066   if (FTI.NumParams > 0) {
3067     // For a declaration with parameters, eg. "T var(T());", suggest adding
3068     // parens around the first parameter to turn the declaration into a
3069     // variable declaration.
3070     SourceRange Range = FTI.Params[0].Param->getSourceRange();
3071     SourceLocation B = Range.getBegin();
3072     SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3073     // FIXME: Maybe we should suggest adding braces instead of parens
3074     // in C++11 for classes that don't have an initializer_list constructor.
3075     S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3076       << FixItHint::CreateInsertion(B, "(")
3077       << FixItHint::CreateInsertion(E, ")");
3078   } else {
3079     // For a declaration without parameters, eg. "T var();", suggest replacing
3080     // the parens with an initializer to turn the declaration into a variable
3081     // declaration.
3082     const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3083 
3084     // Empty parens mean value-initialization, and no parens mean
3085     // default initialization. These are equivalent if the default
3086     // constructor is user-provided or if zero-initialization is a
3087     // no-op.
3088     if (RD && RD->hasDefinition() &&
3089         (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3090       S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3091         << FixItHint::CreateRemoval(ParenRange);
3092     else {
3093       std::string Init =
3094           S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3095       if (Init.empty() && S.LangOpts.CPlusPlus11)
3096         Init = "{}";
3097       if (!Init.empty())
3098         S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3099           << FixItHint::CreateReplacement(ParenRange, Init);
3100     }
3101   }
3102 }
3103 
3104 /// Helper for figuring out the default CC for a function declarator type.  If
3105 /// this is the outermost chunk, then we can determine the CC from the
3106 /// declarator context.  If not, then this could be either a member function
3107 /// type or normal function type.
3108 static CallingConv
3109 getCCForDeclaratorChunk(Sema &S, Declarator &D,
3110                         const DeclaratorChunk::FunctionTypeInfo &FTI,
3111                         unsigned ChunkIndex) {
3112   assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3113 
3114   // Check for an explicit CC attribute.
3115   for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) {
3116     switch (Attr->getKind()) {
3117     CALLING_CONV_ATTRS_CASELIST: {
3118       // Ignore attributes that don't validate or can't apply to the
3119       // function type.  We'll diagnose the failure to apply them in
3120       // handleFunctionTypeAttr.
3121       CallingConv CC;
3122       if (!S.CheckCallingConvAttr(*Attr, CC) &&
3123           (!FTI.isVariadic || supportsVariadicCall(CC))) {
3124         return CC;
3125       }
3126       break;
3127     }
3128 
3129     default:
3130       break;
3131     }
3132   }
3133 
3134   bool IsCXXInstanceMethod = false;
3135 
3136   if (S.getLangOpts().CPlusPlus) {
3137     // Look inwards through parentheses to see if this chunk will form a
3138     // member pointer type or if we're the declarator.  Any type attributes
3139     // between here and there will override the CC we choose here.
3140     unsigned I = ChunkIndex;
3141     bool FoundNonParen = false;
3142     while (I && !FoundNonParen) {
3143       --I;
3144       if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3145         FoundNonParen = true;
3146     }
3147 
3148     if (FoundNonParen) {
3149       // If we're not the declarator, we're a regular function type unless we're
3150       // in a member pointer.
3151       IsCXXInstanceMethod =
3152           D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3153     } else if (D.getContext() == Declarator::LambdaExprContext) {
3154       // This can only be a call operator for a lambda, which is an instance
3155       // method.
3156       IsCXXInstanceMethod = true;
3157     } else {
3158       // We're the innermost decl chunk, so must be a function declarator.
3159       assert(D.isFunctionDeclarator());
3160 
3161       // If we're inside a record, we're declaring a method, but it could be
3162       // explicitly or implicitly static.
3163       IsCXXInstanceMethod =
3164           D.isFirstDeclarationOfMember() &&
3165           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3166           !D.isStaticMember();
3167     }
3168   }
3169 
3170   CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3171                                                          IsCXXInstanceMethod);
3172 
3173   // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3174   // and AMDGPU targets, hence it cannot be treated as a calling
3175   // convention attribute. This is the simplest place to infer
3176   // calling convention for OpenCL kernels.
3177   if (S.getLangOpts().OpenCL) {
3178     for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
3179          Attr; Attr = Attr->getNext()) {
3180       if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
3181         llvm::Triple::ArchType arch = S.Context.getTargetInfo().getTriple().getArch();
3182         if (arch == llvm::Triple::spir || arch == llvm::Triple::spir64 ||
3183             arch == llvm::Triple::amdgcn) {
3184           CC = CC_OpenCLKernel;
3185         }
3186         break;
3187       }
3188     }
3189   }
3190 
3191   return CC;
3192 }
3193 
3194 namespace {
3195   /// A simple notion of pointer kinds, which matches up with the various
3196   /// pointer declarators.
3197   enum class SimplePointerKind {
3198     Pointer,
3199     BlockPointer,
3200     MemberPointer,
3201     Array,
3202   };
3203 } // end anonymous namespace
3204 
3205 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3206   switch (nullability) {
3207   case NullabilityKind::NonNull:
3208     if (!Ident__Nonnull)
3209       Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3210     return Ident__Nonnull;
3211 
3212   case NullabilityKind::Nullable:
3213     if (!Ident__Nullable)
3214       Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3215     return Ident__Nullable;
3216 
3217   case NullabilityKind::Unspecified:
3218     if (!Ident__Null_unspecified)
3219       Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3220     return Ident__Null_unspecified;
3221   }
3222   llvm_unreachable("Unknown nullability kind.");
3223 }
3224 
3225 /// Retrieve the identifier "NSError".
3226 IdentifierInfo *Sema::getNSErrorIdent() {
3227   if (!Ident_NSError)
3228     Ident_NSError = PP.getIdentifierInfo("NSError");
3229 
3230   return Ident_NSError;
3231 }
3232 
3233 /// Check whether there is a nullability attribute of any kind in the given
3234 /// attribute list.
3235 static bool hasNullabilityAttr(const AttributeList *attrs) {
3236   for (const AttributeList *attr = attrs; attr;
3237        attr = attr->getNext()) {
3238     if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3239         attr->getKind() == AttributeList::AT_TypeNullable ||
3240         attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3241       return true;
3242   }
3243 
3244   return false;
3245 }
3246 
3247 namespace {
3248   /// Describes the kind of a pointer a declarator describes.
3249   enum class PointerDeclaratorKind {
3250     // Not a pointer.
3251     NonPointer,
3252     // Single-level pointer.
3253     SingleLevelPointer,
3254     // Multi-level pointer (of any pointer kind).
3255     MultiLevelPointer,
3256     // CFFooRef*
3257     MaybePointerToCFRef,
3258     // CFErrorRef*
3259     CFErrorRefPointer,
3260     // NSError**
3261     NSErrorPointerPointer,
3262   };
3263 
3264   /// Describes a declarator chunk wrapping a pointer that marks inference as
3265   /// unexpected.
3266   // These values must be kept in sync with diagnostics.
3267   enum class PointerWrappingDeclaratorKind {
3268     /// Pointer is top-level.
3269     None = -1,
3270     /// Pointer is an array element.
3271     Array = 0,
3272     /// Pointer is the referent type of a C++ reference.
3273     Reference = 1
3274   };
3275 } // end anonymous namespace
3276 
3277 /// Classify the given declarator, whose type-specified is \c type, based on
3278 /// what kind of pointer it refers to.
3279 ///
3280 /// This is used to determine the default nullability.
3281 static PointerDeclaratorKind
3282 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3283                           PointerWrappingDeclaratorKind &wrappingKind) {
3284   unsigned numNormalPointers = 0;
3285 
3286   // For any dependent type, we consider it a non-pointer.
3287   if (type->isDependentType())
3288     return PointerDeclaratorKind::NonPointer;
3289 
3290   // Look through the declarator chunks to identify pointers.
3291   for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3292     DeclaratorChunk &chunk = declarator.getTypeObject(i);
3293     switch (chunk.Kind) {
3294     case DeclaratorChunk::Array:
3295       if (numNormalPointers == 0)
3296         wrappingKind = PointerWrappingDeclaratorKind::Array;
3297       break;
3298 
3299     case DeclaratorChunk::Function:
3300     case DeclaratorChunk::Pipe:
3301       break;
3302 
3303     case DeclaratorChunk::BlockPointer:
3304     case DeclaratorChunk::MemberPointer:
3305       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3306                                    : PointerDeclaratorKind::SingleLevelPointer;
3307 
3308     case DeclaratorChunk::Paren:
3309       break;
3310 
3311     case DeclaratorChunk::Reference:
3312       if (numNormalPointers == 0)
3313         wrappingKind = PointerWrappingDeclaratorKind::Reference;
3314       break;
3315 
3316     case DeclaratorChunk::Pointer:
3317       ++numNormalPointers;
3318       if (numNormalPointers > 2)
3319         return PointerDeclaratorKind::MultiLevelPointer;
3320       break;
3321     }
3322   }
3323 
3324   // Then, dig into the type specifier itself.
3325   unsigned numTypeSpecifierPointers = 0;
3326   do {
3327     // Decompose normal pointers.
3328     if (auto ptrType = type->getAs<PointerType>()) {
3329       ++numNormalPointers;
3330 
3331       if (numNormalPointers > 2)
3332         return PointerDeclaratorKind::MultiLevelPointer;
3333 
3334       type = ptrType->getPointeeType();
3335       ++numTypeSpecifierPointers;
3336       continue;
3337     }
3338 
3339     // Decompose block pointers.
3340     if (type->getAs<BlockPointerType>()) {
3341       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3342                                    : PointerDeclaratorKind::SingleLevelPointer;
3343     }
3344 
3345     // Decompose member pointers.
3346     if (type->getAs<MemberPointerType>()) {
3347       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3348                                    : PointerDeclaratorKind::SingleLevelPointer;
3349     }
3350 
3351     // Look at Objective-C object pointers.
3352     if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3353       ++numNormalPointers;
3354       ++numTypeSpecifierPointers;
3355 
3356       // If this is NSError**, report that.
3357       if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3358         if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3359             numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3360           return PointerDeclaratorKind::NSErrorPointerPointer;
3361         }
3362       }
3363 
3364       break;
3365     }
3366 
3367     // Look at Objective-C class types.
3368     if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3369       if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3370         if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3371           return PointerDeclaratorKind::NSErrorPointerPointer;;
3372       }
3373 
3374       break;
3375     }
3376 
3377     // If at this point we haven't seen a pointer, we won't see one.
3378     if (numNormalPointers == 0)
3379       return PointerDeclaratorKind::NonPointer;
3380 
3381     if (auto recordType = type->getAs<RecordType>()) {
3382       RecordDecl *recordDecl = recordType->getDecl();
3383 
3384       bool isCFError = false;
3385       if (S.CFError) {
3386         // If we already know about CFError, test it directly.
3387         isCFError = (S.CFError == recordDecl);
3388       } else {
3389         // Check whether this is CFError, which we identify based on its bridge
3390         // to NSError.
3391         if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3392           if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
3393             if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
3394               S.CFError = recordDecl;
3395               isCFError = true;
3396             }
3397           }
3398         }
3399       }
3400 
3401       // If this is CFErrorRef*, report it as such.
3402       if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3403         return PointerDeclaratorKind::CFErrorRefPointer;
3404       }
3405       break;
3406     }
3407 
3408     break;
3409   } while (true);
3410 
3411   switch (numNormalPointers) {
3412   case 0:
3413     return PointerDeclaratorKind::NonPointer;
3414 
3415   case 1:
3416     return PointerDeclaratorKind::SingleLevelPointer;
3417 
3418   case 2:
3419     return PointerDeclaratorKind::MaybePointerToCFRef;
3420 
3421   default:
3422     return PointerDeclaratorKind::MultiLevelPointer;
3423   }
3424 }
3425 
3426 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3427                                                     SourceLocation loc) {
3428   // If we're anywhere in a function, method, or closure context, don't perform
3429   // completeness checks.
3430   for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3431     if (ctx->isFunctionOrMethod())
3432       return FileID();
3433 
3434     if (ctx->isFileContext())
3435       break;
3436   }
3437 
3438   // We only care about the expansion location.
3439   loc = S.SourceMgr.getExpansionLoc(loc);
3440   FileID file = S.SourceMgr.getFileID(loc);
3441   if (file.isInvalid())
3442     return FileID();
3443 
3444   // Retrieve file information.
3445   bool invalid = false;
3446   const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3447   if (invalid || !sloc.isFile())
3448     return FileID();
3449 
3450   // We don't want to perform completeness checks on the main file or in
3451   // system headers.
3452   const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3453   if (fileInfo.getIncludeLoc().isInvalid())
3454     return FileID();
3455   if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3456       S.Diags.getSuppressSystemWarnings()) {
3457     return FileID();
3458   }
3459 
3460   return file;
3461 }
3462 
3463 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3464 /// taking into account whitespace before and after.
3465 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
3466                              SourceLocation PointerLoc,
3467                              NullabilityKind Nullability) {
3468   assert(PointerLoc.isValid());
3469   if (PointerLoc.isMacroID())
3470     return;
3471 
3472   SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3473   if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3474     return;
3475 
3476   const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3477   if (!NextChar)
3478     return;
3479 
3480   SmallString<32> InsertionTextBuf{" "};
3481   InsertionTextBuf += getNullabilitySpelling(Nullability);
3482   InsertionTextBuf += " ";
3483   StringRef InsertionText = InsertionTextBuf.str();
3484 
3485   if (isWhitespace(*NextChar)) {
3486     InsertionText = InsertionText.drop_back();
3487   } else if (NextChar[-1] == '[') {
3488     if (NextChar[0] == ']')
3489       InsertionText = InsertionText.drop_back().drop_front();
3490     else
3491       InsertionText = InsertionText.drop_front();
3492   } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3493              !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3494     InsertionText = InsertionText.drop_back().drop_front();
3495   }
3496 
3497   Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3498 }
3499 
3500 static void emitNullabilityConsistencyWarning(Sema &S,
3501                                               SimplePointerKind PointerKind,
3502                                               SourceLocation PointerLoc) {
3503   assert(PointerLoc.isValid());
3504 
3505   if (PointerKind == SimplePointerKind::Array) {
3506     S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3507   } else {
3508     S.Diag(PointerLoc, diag::warn_nullability_missing)
3509       << static_cast<unsigned>(PointerKind);
3510   }
3511 
3512   if (PointerLoc.isMacroID())
3513     return;
3514 
3515   auto addFixIt = [&](NullabilityKind Nullability) {
3516     auto Diag = S.Diag(PointerLoc, diag::note_nullability_fix_it);
3517     Diag << static_cast<unsigned>(Nullability);
3518     Diag << static_cast<unsigned>(PointerKind);
3519     fixItNullability(S, Diag, PointerLoc, Nullability);
3520   };
3521   addFixIt(NullabilityKind::Nullable);
3522   addFixIt(NullabilityKind::NonNull);
3523 }
3524 
3525 /// Complains about missing nullability if the file containing \p pointerLoc
3526 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3527 /// pragma).
3528 ///
3529 /// If the file has \e not seen other uses of nullability, this particular
3530 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3531 static void checkNullabilityConsistency(Sema &S,
3532                                         SimplePointerKind pointerKind,
3533                                         SourceLocation pointerLoc) {
3534   // Determine which file we're performing consistency checking for.
3535   FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3536   if (file.isInvalid())
3537     return;
3538 
3539   // If we haven't seen any type nullability in this file, we won't warn now
3540   // about anything.
3541   FileNullability &fileNullability = S.NullabilityMap[file];
3542   if (!fileNullability.SawTypeNullability) {
3543     // If this is the first pointer declarator in the file, and the appropriate
3544     // warning is on, record it in case we need to diagnose it retroactively.
3545     diag::kind diagKind;
3546     if (pointerKind == SimplePointerKind::Array)
3547       diagKind = diag::warn_nullability_missing_array;
3548     else
3549       diagKind = diag::warn_nullability_missing;
3550 
3551     if (fileNullability.PointerLoc.isInvalid() &&
3552         !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3553       fileNullability.PointerLoc = pointerLoc;
3554       fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3555     }
3556 
3557     return;
3558   }
3559 
3560   // Complain about missing nullability.
3561   emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc);
3562 }
3563 
3564 /// Marks that a nullability feature has been used in the file containing
3565 /// \p loc.
3566 ///
3567 /// If this file already had pointer types in it that were missing nullability,
3568 /// the first such instance is retroactively diagnosed.
3569 ///
3570 /// \sa checkNullabilityConsistency
3571 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
3572   FileID file = getNullabilityCompletenessCheckFileID(S, loc);
3573   if (file.isInvalid())
3574     return;
3575 
3576   FileNullability &fileNullability = S.NullabilityMap[file];
3577   if (fileNullability.SawTypeNullability)
3578     return;
3579   fileNullability.SawTypeNullability = true;
3580 
3581   // If we haven't seen any type nullability before, now we have. Retroactively
3582   // diagnose the first unannotated pointer, if there was one.
3583   if (fileNullability.PointerLoc.isInvalid())
3584     return;
3585 
3586   auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3587   emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc);
3588 }
3589 
3590 /// Returns true if any of the declarator chunks before \p endIndex include a
3591 /// level of indirection: array, pointer, reference, or pointer-to-member.
3592 ///
3593 /// Because declarator chunks are stored in outer-to-inner order, testing
3594 /// every chunk before \p endIndex is testing all chunks that embed the current
3595 /// chunk as part of their type.
3596 ///
3597 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3598 /// end index, in which case all chunks are tested.
3599 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3600   unsigned i = endIndex;
3601   while (i != 0) {
3602     // Walk outwards along the declarator chunks.
3603     --i;
3604     const DeclaratorChunk &DC = D.getTypeObject(i);
3605     switch (DC.Kind) {
3606     case DeclaratorChunk::Paren:
3607       break;
3608     case DeclaratorChunk::Array:
3609     case DeclaratorChunk::Pointer:
3610     case DeclaratorChunk::Reference:
3611     case DeclaratorChunk::MemberPointer:
3612       return true;
3613     case DeclaratorChunk::Function:
3614     case DeclaratorChunk::BlockPointer:
3615     case DeclaratorChunk::Pipe:
3616       // These are invalid anyway, so just ignore.
3617       break;
3618     }
3619   }
3620   return false;
3621 }
3622 
3623 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3624                                                 QualType declSpecType,
3625                                                 TypeSourceInfo *TInfo) {
3626   // The TypeSourceInfo that this function returns will not be a null type.
3627   // If there is an error, this function will fill in a dummy type as fallback.
3628   QualType T = declSpecType;
3629   Declarator &D = state.getDeclarator();
3630   Sema &S = state.getSema();
3631   ASTContext &Context = S.Context;
3632   const LangOptions &LangOpts = S.getLangOpts();
3633 
3634   // The name we're declaring, if any.
3635   DeclarationName Name;
3636   if (D.getIdentifier())
3637     Name = D.getIdentifier();
3638 
3639   // Does this declaration declare a typedef-name?
3640   bool IsTypedefName =
3641     D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3642     D.getContext() == Declarator::AliasDeclContext ||
3643     D.getContext() == Declarator::AliasTemplateContext;
3644 
3645   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3646   bool IsQualifiedFunction = T->isFunctionProtoType() &&
3647       (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3648        T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3649 
3650   // If T is 'decltype(auto)', the only declarators we can have are parens
3651   // and at most one function declarator if this is a function declaration.
3652   // If T is a deduced class template specialization type, we can have no
3653   // declarator chunks at all.
3654   if (auto *DT = T->getAs<DeducedType>()) {
3655     const AutoType *AT = T->getAs<AutoType>();
3656     bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
3657     if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
3658       for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3659         unsigned Index = E - I - 1;
3660         DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3661         unsigned DiagId = IsClassTemplateDeduction
3662                               ? diag::err_deduced_class_template_compound_type
3663                               : diag::err_decltype_auto_compound_type;
3664         unsigned DiagKind = 0;
3665         switch (DeclChunk.Kind) {
3666         case DeclaratorChunk::Paren:
3667           // FIXME: Rejecting this is a little silly.
3668           if (IsClassTemplateDeduction) {
3669             DiagKind = 4;
3670             break;
3671           }
3672           continue;
3673         case DeclaratorChunk::Function: {
3674           if (IsClassTemplateDeduction) {
3675             DiagKind = 3;
3676             break;
3677           }
3678           unsigned FnIndex;
3679           if (D.isFunctionDeclarationContext() &&
3680               D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3681             continue;
3682           DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3683           break;
3684         }
3685         case DeclaratorChunk::Pointer:
3686         case DeclaratorChunk::BlockPointer:
3687         case DeclaratorChunk::MemberPointer:
3688           DiagKind = 0;
3689           break;
3690         case DeclaratorChunk::Reference:
3691           DiagKind = 1;
3692           break;
3693         case DeclaratorChunk::Array:
3694           DiagKind = 2;
3695           break;
3696         case DeclaratorChunk::Pipe:
3697           break;
3698         }
3699 
3700         S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3701         D.setInvalidType(true);
3702         break;
3703       }
3704     }
3705   }
3706 
3707   // Determine whether we should infer _Nonnull on pointer types.
3708   Optional<NullabilityKind> inferNullability;
3709   bool inferNullabilityCS = false;
3710   bool inferNullabilityInnerOnly = false;
3711   bool inferNullabilityInnerOnlyComplete = false;
3712 
3713   // Are we in an assume-nonnull region?
3714   bool inAssumeNonNullRegion = false;
3715   SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
3716   if (assumeNonNullLoc.isValid()) {
3717     inAssumeNonNullRegion = true;
3718     recordNullabilitySeen(S, assumeNonNullLoc);
3719   }
3720 
3721   // Whether to complain about missing nullability specifiers or not.
3722   enum {
3723     /// Never complain.
3724     CAMN_No,
3725     /// Complain on the inner pointers (but not the outermost
3726     /// pointer).
3727     CAMN_InnerPointers,
3728     /// Complain about any pointers that don't have nullability
3729     /// specified or inferred.
3730     CAMN_Yes
3731   } complainAboutMissingNullability = CAMN_No;
3732   unsigned NumPointersRemaining = 0;
3733   auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
3734 
3735   if (IsTypedefName) {
3736     // For typedefs, we do not infer any nullability (the default),
3737     // and we only complain about missing nullability specifiers on
3738     // inner pointers.
3739     complainAboutMissingNullability = CAMN_InnerPointers;
3740 
3741     auto isDependentNonPointerType = [](QualType T) -> bool {
3742       // Note: This is intended to be the same check as Type::canHaveNullability
3743       // except with all of the ambiguous cases being treated as 'false' rather
3744       // than 'true'.
3745       return T->isDependentType() && !T->isAnyPointerType() &&
3746         !T->isBlockPointerType() && !T->isMemberPointerType();
3747     };
3748 
3749     if (T->canHaveNullability() && !T->getNullability(S.Context) &&
3750         !isDependentNonPointerType(T)) {
3751       // Note that we allow but don't require nullability on dependent types.
3752       ++NumPointersRemaining;
3753     }
3754 
3755     for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3756       DeclaratorChunk &chunk = D.getTypeObject(i);
3757       switch (chunk.Kind) {
3758       case DeclaratorChunk::Array:
3759       case DeclaratorChunk::Function:
3760       case DeclaratorChunk::Pipe:
3761         break;
3762 
3763       case DeclaratorChunk::BlockPointer:
3764       case DeclaratorChunk::MemberPointer:
3765         ++NumPointersRemaining;
3766         break;
3767 
3768       case DeclaratorChunk::Paren:
3769       case DeclaratorChunk::Reference:
3770         continue;
3771 
3772       case DeclaratorChunk::Pointer:
3773         ++NumPointersRemaining;
3774         continue;
3775       }
3776     }
3777   } else {
3778     bool isFunctionOrMethod = false;
3779     switch (auto context = state.getDeclarator().getContext()) {
3780     case Declarator::ObjCParameterContext:
3781     case Declarator::ObjCResultContext:
3782     case Declarator::PrototypeContext:
3783     case Declarator::TrailingReturnContext:
3784       isFunctionOrMethod = true;
3785       // fallthrough
3786 
3787     case Declarator::MemberContext:
3788       if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3789         complainAboutMissingNullability = CAMN_No;
3790         break;
3791       }
3792 
3793       // Weak properties are inferred to be nullable.
3794       if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3795         inferNullability = NullabilityKind::Nullable;
3796         break;
3797       }
3798 
3799       // fallthrough
3800 
3801     case Declarator::FileContext:
3802     case Declarator::KNRTypeListContext: {
3803       complainAboutMissingNullability = CAMN_Yes;
3804 
3805       // Nullability inference depends on the type and declarator.
3806       auto wrappingKind = PointerWrappingDeclaratorKind::None;
3807       switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
3808       case PointerDeclaratorKind::NonPointer:
3809       case PointerDeclaratorKind::MultiLevelPointer:
3810         // Cannot infer nullability.
3811         break;
3812 
3813       case PointerDeclaratorKind::SingleLevelPointer:
3814         // Infer _Nonnull if we are in an assumes-nonnull region.
3815         if (inAssumeNonNullRegion) {
3816           complainAboutInferringWithinChunk = wrappingKind;
3817           inferNullability = NullabilityKind::NonNull;
3818           inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3819                                 context == Declarator::ObjCResultContext);
3820         }
3821         break;
3822 
3823       case PointerDeclaratorKind::CFErrorRefPointer:
3824       case PointerDeclaratorKind::NSErrorPointerPointer:
3825         // Within a function or method signature, infer _Nullable at both
3826         // levels.
3827         if (isFunctionOrMethod && inAssumeNonNullRegion)
3828           inferNullability = NullabilityKind::Nullable;
3829         break;
3830 
3831       case PointerDeclaratorKind::MaybePointerToCFRef:
3832         if (isFunctionOrMethod) {
3833           // On pointer-to-pointer parameters marked cf_returns_retained or
3834           // cf_returns_not_retained, if the outer pointer is explicit then
3835           // infer the inner pointer as _Nullable.
3836           auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3837             while (NextAttr) {
3838               if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3839                   NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3840                 return true;
3841               NextAttr = NextAttr->getNext();
3842             }
3843             return false;
3844           };
3845           if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3846             if (hasCFReturnsAttr(D.getAttributes()) ||
3847                 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3848                 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3849               inferNullability = NullabilityKind::Nullable;
3850               inferNullabilityInnerOnly = true;
3851             }
3852           }
3853         }
3854         break;
3855       }
3856       break;
3857     }
3858 
3859     case Declarator::ConversionIdContext:
3860       complainAboutMissingNullability = CAMN_Yes;
3861       break;
3862 
3863     case Declarator::AliasDeclContext:
3864     case Declarator::AliasTemplateContext:
3865     case Declarator::BlockContext:
3866     case Declarator::BlockLiteralContext:
3867     case Declarator::ConditionContext:
3868     case Declarator::CXXCatchContext:
3869     case Declarator::CXXNewContext:
3870     case Declarator::ForContext:
3871     case Declarator::InitStmtContext:
3872     case Declarator::LambdaExprContext:
3873     case Declarator::LambdaExprParameterContext:
3874     case Declarator::ObjCCatchContext:
3875     case Declarator::TemplateParamContext:
3876     case Declarator::TemplateTypeArgContext:
3877     case Declarator::TypeNameContext:
3878     case Declarator::FunctionalCastContext:
3879       // Don't infer in these contexts.
3880       break;
3881     }
3882   }
3883 
3884   // Local function that returns true if its argument looks like a va_list.
3885   auto isVaList = [&S](QualType T) -> bool {
3886     auto *typedefTy = T->getAs<TypedefType>();
3887     if (!typedefTy)
3888       return false;
3889     TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
3890     do {
3891       if (typedefTy->getDecl() == vaListTypedef)
3892         return true;
3893       if (auto *name = typedefTy->getDecl()->getIdentifier())
3894         if (name->isStr("va_list"))
3895           return true;
3896       typedefTy = typedefTy->desugar()->getAs<TypedefType>();
3897     } while (typedefTy);
3898     return false;
3899   };
3900 
3901   // Local function that checks the nullability for a given pointer declarator.
3902   // Returns true if _Nonnull was inferred.
3903   auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3904                                      SourceLocation pointerLoc,
3905                                      AttributeList *&attrs) -> AttributeList * {
3906     // We've seen a pointer.
3907     if (NumPointersRemaining > 0)
3908       --NumPointersRemaining;
3909 
3910     // If a nullability attribute is present, there's nothing to do.
3911     if (hasNullabilityAttr(attrs))
3912       return nullptr;
3913 
3914     // If we're supposed to infer nullability, do so now.
3915     if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3916       AttributeList::Syntax syntax
3917         = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3918                              : AttributeList::AS_Keyword;
3919       AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3920                                          .create(
3921                                            S.getNullabilityKeyword(
3922                                              *inferNullability),
3923                                            SourceRange(pointerLoc),
3924                                            nullptr, SourceLocation(),
3925                                            nullptr, 0, syntax);
3926 
3927       spliceAttrIntoList(*nullabilityAttr, attrs);
3928 
3929       if (inferNullabilityCS) {
3930         state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3931           ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3932       }
3933 
3934       if (pointerLoc.isValid() &&
3935           complainAboutInferringWithinChunk !=
3936             PointerWrappingDeclaratorKind::None) {
3937         auto Diag =
3938             S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
3939         Diag << static_cast<int>(complainAboutInferringWithinChunk);
3940         fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
3941       }
3942 
3943       if (inferNullabilityInnerOnly)
3944         inferNullabilityInnerOnlyComplete = true;
3945       return nullabilityAttr;
3946     }
3947 
3948     // If we're supposed to complain about missing nullability, do so
3949     // now if it's truly missing.
3950     switch (complainAboutMissingNullability) {
3951     case CAMN_No:
3952       break;
3953 
3954     case CAMN_InnerPointers:
3955       if (NumPointersRemaining == 0)
3956         break;
3957       // Fallthrough.
3958 
3959     case CAMN_Yes:
3960       checkNullabilityConsistency(S, pointerKind, pointerLoc);
3961     }
3962     return nullptr;
3963   };
3964 
3965   // If the type itself could have nullability but does not, infer pointer
3966   // nullability and perform consistency checking.
3967   if (S.ActiveTemplateInstantiations.empty()) {
3968     if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3969       if (isVaList(T)) {
3970         // Record that we've seen a pointer, but do nothing else.
3971         if (NumPointersRemaining > 0)
3972           --NumPointersRemaining;
3973       } else {
3974         SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3975         if (T->isBlockPointerType())
3976           pointerKind = SimplePointerKind::BlockPointer;
3977         else if (T->isMemberPointerType())
3978           pointerKind = SimplePointerKind::MemberPointer;
3979 
3980         if (auto *attr = inferPointerNullability(
3981               pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3982               D.getMutableDeclSpec().getAttributes().getListRef())) {
3983           T = Context.getAttributedType(
3984                 AttributedType::getNullabilityAttrKind(*inferNullability),T,T);
3985           attr->setUsedAsTypeAttr();
3986         }
3987       }
3988     }
3989 
3990     if (complainAboutMissingNullability == CAMN_Yes &&
3991         T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
3992         D.isPrototypeContext() &&
3993         !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
3994       checkNullabilityConsistency(S, SimplePointerKind::Array,
3995                                   D.getDeclSpec().getTypeSpecTypeLoc());
3996     }
3997   }
3998 
3999   // Walk the DeclTypeInfo, building the recursive type as we go.
4000   // DeclTypeInfos are ordered from the identifier out, which is
4001   // opposite of what we want :).
4002   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4003     unsigned chunkIndex = e - i - 1;
4004     state.setCurrentChunkIndex(chunkIndex);
4005     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4006     IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4007     switch (DeclType.Kind) {
4008     case DeclaratorChunk::Paren:
4009       T = S.BuildParenType(T);
4010       break;
4011     case DeclaratorChunk::BlockPointer:
4012       // If blocks are disabled, emit an error.
4013       if (!LangOpts.Blocks)
4014         S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4015 
4016       // Handle pointer nullability.
4017       inferPointerNullability(SimplePointerKind::BlockPointer,
4018                               DeclType.Loc, DeclType.getAttrListRef());
4019 
4020       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4021       if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4022         // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4023         // qualified with const.
4024         if (LangOpts.OpenCL)
4025           DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4026         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4027       }
4028       break;
4029     case DeclaratorChunk::Pointer:
4030       // Verify that we're not building a pointer to pointer to function with
4031       // exception specification.
4032       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4033         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4034         D.setInvalidType(true);
4035         // Build the type anyway.
4036       }
4037 
4038       // Handle pointer nullability
4039       inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4040                               DeclType.getAttrListRef());
4041 
4042       if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
4043         T = Context.getObjCObjectPointerType(T);
4044         if (DeclType.Ptr.TypeQuals)
4045           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4046         break;
4047       }
4048 
4049       // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4050       // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4051       // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4052       if (LangOpts.OpenCL) {
4053         if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4054             T->isBlockPointerType()) {
4055           S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4056           D.setInvalidType(true);
4057         }
4058       }
4059 
4060       T = S.BuildPointerType(T, DeclType.Loc, Name);
4061       if (DeclType.Ptr.TypeQuals)
4062         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4063       break;
4064     case DeclaratorChunk::Reference: {
4065       // Verify that we're not building a reference to pointer to function with
4066       // exception specification.
4067       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4068         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4069         D.setInvalidType(true);
4070         // Build the type anyway.
4071       }
4072       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4073 
4074       if (DeclType.Ref.HasRestrict)
4075         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4076       break;
4077     }
4078     case DeclaratorChunk::Array: {
4079       // Verify that we're not building an array of pointers to function with
4080       // exception specification.
4081       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4082         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4083         D.setInvalidType(true);
4084         // Build the type anyway.
4085       }
4086       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4087       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4088       ArrayType::ArraySizeModifier ASM;
4089       if (ATI.isStar)
4090         ASM = ArrayType::Star;
4091       else if (ATI.hasStatic)
4092         ASM = ArrayType::Static;
4093       else
4094         ASM = ArrayType::Normal;
4095       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4096         // FIXME: This check isn't quite right: it allows star in prototypes
4097         // for function definitions, and disallows some edge cases detailed
4098         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4099         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4100         ASM = ArrayType::Normal;
4101         D.setInvalidType(true);
4102       }
4103 
4104       // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4105       // shall appear only in a declaration of a function parameter with an
4106       // array type, ...
4107       if (ASM == ArrayType::Static || ATI.TypeQuals) {
4108         if (!(D.isPrototypeContext() ||
4109               D.getContext() == Declarator::KNRTypeListContext)) {
4110           S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4111               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4112           // Remove the 'static' and the type qualifiers.
4113           if (ASM == ArrayType::Static)
4114             ASM = ArrayType::Normal;
4115           ATI.TypeQuals = 0;
4116           D.setInvalidType(true);
4117         }
4118 
4119         // C99 6.7.5.2p1: ... and then only in the outermost array type
4120         // derivation.
4121         if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4122           S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4123             (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4124           if (ASM == ArrayType::Static)
4125             ASM = ArrayType::Normal;
4126           ATI.TypeQuals = 0;
4127           D.setInvalidType(true);
4128         }
4129       }
4130       const AutoType *AT = T->getContainedAutoType();
4131       // Allow arrays of auto if we are a generic lambda parameter.
4132       // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4133       if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
4134         // We've already diagnosed this for decltype(auto).
4135         if (!AT->isDecltypeAuto())
4136           S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4137             << getPrintableNameForEntity(Name) << T;
4138         T = QualType();
4139         break;
4140       }
4141 
4142       // Array parameters can be marked nullable as well, although it's not
4143       // necessary if they're marked 'static'.
4144       if (complainAboutMissingNullability == CAMN_Yes &&
4145           !hasNullabilityAttr(DeclType.getAttrs()) &&
4146           ASM != ArrayType::Static &&
4147           D.isPrototypeContext() &&
4148           !hasOuterPointerLikeChunk(D, chunkIndex)) {
4149         checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4150       }
4151 
4152       T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4153                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4154       break;
4155     }
4156     case DeclaratorChunk::Function: {
4157       // If the function declarator has a prototype (i.e. it is not () and
4158       // does not have a K&R-style identifier list), then the arguments are part
4159       // of the type, otherwise the argument list is ().
4160       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4161       IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
4162 
4163       // Check for auto functions and trailing return type and adjust the
4164       // return type accordingly.
4165       if (!D.isInvalidType()) {
4166         // trailing-return-type is only required if we're declaring a function,
4167         // and not, for instance, a pointer to a function.
4168         if (D.getDeclSpec().containsPlaceholderType() &&
4169             !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
4170             !S.getLangOpts().CPlusPlus14) {
4171           S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4172                  D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4173                      ? diag::err_auto_missing_trailing_return
4174                      : diag::err_deduced_return_type);
4175           T = Context.IntTy;
4176           D.setInvalidType(true);
4177         } else if (FTI.hasTrailingReturnType()) {
4178           // T must be exactly 'auto' at this point. See CWG issue 681.
4179           if (isa<ParenType>(T)) {
4180             S.Diag(D.getLocStart(),
4181                  diag::err_trailing_return_in_parens)
4182               << T << D.getSourceRange();
4183             D.setInvalidType(true);
4184           } else if (D.getContext() != Declarator::LambdaExprContext &&
4185                      (T.hasQualifiers() || !isa<AutoType>(T) ||
4186                       cast<AutoType>(T)->getKeyword() !=
4187                           AutoTypeKeyword::Auto)) {
4188             if (D.getName().getKind() == UnqualifiedId::IK_DeductionGuideName)
4189               S.Diag(D.getDeclSpec().getLocStart(),
4190                      diag::err_deduction_guide_with_complex_decl)
4191                   << D.getSourceRange();
4192             else
4193               S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4194                      diag::err_trailing_return_without_auto)
4195                   << T << D.getDeclSpec().getSourceRange();
4196             D.setInvalidType(true);
4197           }
4198           T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4199           if (T.isNull()) {
4200             // An error occurred parsing the trailing return type.
4201             T = Context.IntTy;
4202             D.setInvalidType(true);
4203           }
4204         }
4205       }
4206 
4207       // C99 6.7.5.3p1: The return type may not be a function or array type.
4208       // For conversion functions, we'll diagnose this particular error later.
4209       if ((T->isArrayType() || T->isFunctionType()) &&
4210           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
4211         unsigned diagID = diag::err_func_returning_array_function;
4212         // Last processing chunk in block context means this function chunk
4213         // represents the block.
4214         if (chunkIndex == 0 &&
4215             D.getContext() == Declarator::BlockLiteralContext)
4216           diagID = diag::err_block_returning_array_function;
4217         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4218         T = Context.IntTy;
4219         D.setInvalidType(true);
4220       }
4221 
4222       // Do not allow returning half FP value.
4223       // FIXME: This really should be in BuildFunctionType.
4224       if (T->isHalfType()) {
4225         if (S.getLangOpts().OpenCL) {
4226           if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4227             S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4228                 << T << 0 /*pointer hint*/;
4229             D.setInvalidType(true);
4230           }
4231         } else if (!S.getLangOpts().HalfArgsAndReturns) {
4232           S.Diag(D.getIdentifierLoc(),
4233             diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4234           D.setInvalidType(true);
4235         }
4236       }
4237 
4238       if (LangOpts.OpenCL) {
4239         // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4240         // function.
4241         if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4242             T->isPipeType()) {
4243           S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4244               << T << 1 /*hint off*/;
4245           D.setInvalidType(true);
4246         }
4247         // OpenCL doesn't support variadic functions and blocks
4248         // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4249         // We also allow here any toolchain reserved identifiers.
4250         if (FTI.isVariadic &&
4251             !(D.getIdentifier() &&
4252               ((D.getIdentifier()->getName() == "printf" &&
4253                 LangOpts.OpenCLVersion >= 120) ||
4254                D.getIdentifier()->getName().startswith("__")))) {
4255           S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4256           D.setInvalidType(true);
4257         }
4258       }
4259 
4260       // Methods cannot return interface types. All ObjC objects are
4261       // passed by reference.
4262       if (T->isObjCObjectType()) {
4263         SourceLocation DiagLoc, FixitLoc;
4264         if (TInfo) {
4265           DiagLoc = TInfo->getTypeLoc().getLocStart();
4266           FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4267         } else {
4268           DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4269           FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4270         }
4271         S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4272           << 0 << T
4273           << FixItHint::CreateInsertion(FixitLoc, "*");
4274 
4275         T = Context.getObjCObjectPointerType(T);
4276         if (TInfo) {
4277           TypeLocBuilder TLB;
4278           TLB.pushFullCopy(TInfo->getTypeLoc());
4279           ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4280           TLoc.setStarLoc(FixitLoc);
4281           TInfo = TLB.getTypeSourceInfo(Context, T);
4282         }
4283 
4284         D.setInvalidType(true);
4285       }
4286 
4287       // cv-qualifiers on return types are pointless except when the type is a
4288       // class type in C++.
4289       if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4290           !(S.getLangOpts().CPlusPlus &&
4291             (T->isDependentType() || T->isRecordType()))) {
4292         if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4293             D.getFunctionDefinitionKind() == FDK_Definition) {
4294           // [6.9.1/3] qualified void return is invalid on a C
4295           // function definition.  Apparently ok on declarations and
4296           // in C++ though (!)
4297           S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4298         } else
4299           diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4300       }
4301 
4302       // Objective-C ARC ownership qualifiers are ignored on the function
4303       // return type (by type canonicalization). Complain if this attribute
4304       // was written here.
4305       if (T.getQualifiers().hasObjCLifetime()) {
4306         SourceLocation AttrLoc;
4307         if (chunkIndex + 1 < D.getNumTypeObjects()) {
4308           DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4309           for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
4310                Attr; Attr = Attr->getNext()) {
4311             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4312               AttrLoc = Attr->getLoc();
4313               break;
4314             }
4315           }
4316         }
4317         if (AttrLoc.isInvalid()) {
4318           for (const AttributeList *Attr
4319                  = D.getDeclSpec().getAttributes().getList();
4320                Attr; Attr = Attr->getNext()) {
4321             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4322               AttrLoc = Attr->getLoc();
4323               break;
4324             }
4325           }
4326         }
4327 
4328         if (AttrLoc.isValid()) {
4329           // The ownership attributes are almost always written via
4330           // the predefined
4331           // __strong/__weak/__autoreleasing/__unsafe_unretained.
4332           if (AttrLoc.isMacroID())
4333             AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
4334 
4335           S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4336             << T.getQualifiers().getObjCLifetime();
4337         }
4338       }
4339 
4340       if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4341         // C++ [dcl.fct]p6:
4342         //   Types shall not be defined in return or parameter types.
4343         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4344         S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4345           << Context.getTypeDeclType(Tag);
4346       }
4347 
4348       // Exception specs are not allowed in typedefs. Complain, but add it
4349       // anyway.
4350       if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus1z)
4351         S.Diag(FTI.getExceptionSpecLocBeg(),
4352                diag::err_exception_spec_in_typedef)
4353             << (D.getContext() == Declarator::AliasDeclContext ||
4354                 D.getContext() == Declarator::AliasTemplateContext);
4355 
4356       // If we see "T var();" or "T var(T());" at block scope, it is probably
4357       // an attempt to initialize a variable, not a function declaration.
4358       if (FTI.isAmbiguous)
4359         warnAboutAmbiguousFunction(S, D, DeclType, T);
4360 
4361       // GNU warning -Wstrict-prototypes
4362       //   Warn if a function declaration is without a prototype.
4363       //   This warning is issued for all kinds of unprototyped function
4364       //   declarations (i.e. function type typedef, function pointer etc.)
4365       //   C99 6.7.5.3p14:
4366       //   The empty list in a function declarator that is not part of a
4367       //   definition of that function specifies that no information
4368       //   about the number or types of the parameters is supplied.
4369       if (D.getFunctionDefinitionKind() == FDK_Declaration &&
4370           FTI.NumParams == 0 && !LangOpts.CPlusPlus)
4371         S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4372             << 0 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4373 
4374       FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
4375 
4376       if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
4377         // Simple void foo(), where the incoming T is the result type.
4378         T = Context.getFunctionNoProtoType(T, EI);
4379       } else {
4380         // We allow a zero-parameter variadic function in C if the
4381         // function is marked with the "overloadable" attribute. Scan
4382         // for this attribute now.
4383         if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
4384           bool Overloadable = false;
4385           for (const AttributeList *Attrs = D.getAttributes();
4386                Attrs; Attrs = Attrs->getNext()) {
4387             if (Attrs->getKind() == AttributeList::AT_Overloadable) {
4388               Overloadable = true;
4389               break;
4390             }
4391           }
4392 
4393           if (!Overloadable)
4394             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4395         }
4396 
4397         if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4398           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4399           // definition.
4400           S.Diag(FTI.Params[0].IdentLoc,
4401                  diag::err_ident_list_in_fn_declaration);
4402           D.setInvalidType(true);
4403           // Recover by creating a K&R-style function type.
4404           T = Context.getFunctionNoProtoType(T, EI);
4405           break;
4406         }
4407 
4408         FunctionProtoType::ExtProtoInfo EPI;
4409         EPI.ExtInfo = EI;
4410         EPI.Variadic = FTI.isVariadic;
4411         EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4412         EPI.TypeQuals = FTI.TypeQuals;
4413         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4414                     : FTI.RefQualifierIsLValueRef? RQ_LValue
4415                     : RQ_RValue;
4416 
4417         // Otherwise, we have a function with a parameter list that is
4418         // potentially variadic.
4419         SmallVector<QualType, 16> ParamTys;
4420         ParamTys.reserve(FTI.NumParams);
4421 
4422         SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4423           ExtParameterInfos(FTI.NumParams);
4424         bool HasAnyInterestingExtParameterInfos = false;
4425 
4426         for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4427           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4428           QualType ParamTy = Param->getType();
4429           assert(!ParamTy.isNull() && "Couldn't parse type?");
4430 
4431           // Look for 'void'.  void is allowed only as a single parameter to a
4432           // function with no other parameters (C99 6.7.5.3p10).  We record
4433           // int(void) as a FunctionProtoType with an empty parameter list.
4434           if (ParamTy->isVoidType()) {
4435             // If this is something like 'float(int, void)', reject it.  'void'
4436             // is an incomplete type (C99 6.2.5p19) and function decls cannot
4437             // have parameters of incomplete type.
4438             if (FTI.NumParams != 1 || FTI.isVariadic) {
4439               S.Diag(DeclType.Loc, diag::err_void_only_param);
4440               ParamTy = Context.IntTy;
4441               Param->setType(ParamTy);
4442             } else if (FTI.Params[i].Ident) {
4443               // Reject, but continue to parse 'int(void abc)'.
4444               S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4445               ParamTy = Context.IntTy;
4446               Param->setType(ParamTy);
4447             } else {
4448               // Reject, but continue to parse 'float(const void)'.
4449               if (ParamTy.hasQualifiers())
4450                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4451 
4452               // Do not add 'void' to the list.
4453               break;
4454             }
4455           } else if (ParamTy->isHalfType()) {
4456             // Disallow half FP parameters.
4457             // FIXME: This really should be in BuildFunctionType.
4458             if (S.getLangOpts().OpenCL) {
4459               if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4460                 S.Diag(Param->getLocation(),
4461                   diag::err_opencl_half_param) << ParamTy;
4462                 D.setInvalidType();
4463                 Param->setInvalidDecl();
4464               }
4465             } else if (!S.getLangOpts().HalfArgsAndReturns) {
4466               S.Diag(Param->getLocation(),
4467                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4468               D.setInvalidType();
4469             }
4470           } else if (!FTI.hasPrototype) {
4471             if (ParamTy->isPromotableIntegerType()) {
4472               ParamTy = Context.getPromotedIntegerType(ParamTy);
4473               Param->setKNRPromoted(true);
4474             } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4475               if (BTy->getKind() == BuiltinType::Float) {
4476                 ParamTy = Context.DoubleTy;
4477                 Param->setKNRPromoted(true);
4478               }
4479             }
4480           }
4481 
4482           if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4483             ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4484             HasAnyInterestingExtParameterInfos = true;
4485           }
4486 
4487           if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4488             ExtParameterInfos[i] =
4489               ExtParameterInfos[i].withABI(attr->getABI());
4490             HasAnyInterestingExtParameterInfos = true;
4491           }
4492 
4493           ParamTys.push_back(ParamTy);
4494         }
4495 
4496         if (HasAnyInterestingExtParameterInfos) {
4497           EPI.ExtParameterInfos = ExtParameterInfos.data();
4498           checkExtParameterInfos(S, ParamTys, EPI,
4499               [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4500         }
4501 
4502         SmallVector<QualType, 4> Exceptions;
4503         SmallVector<ParsedType, 2> DynamicExceptions;
4504         SmallVector<SourceRange, 2> DynamicExceptionRanges;
4505         Expr *NoexceptExpr = nullptr;
4506 
4507         if (FTI.getExceptionSpecType() == EST_Dynamic) {
4508           // FIXME: It's rather inefficient to have to split into two vectors
4509           // here.
4510           unsigned N = FTI.getNumExceptions();
4511           DynamicExceptions.reserve(N);
4512           DynamicExceptionRanges.reserve(N);
4513           for (unsigned I = 0; I != N; ++I) {
4514             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4515             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4516           }
4517         } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4518           NoexceptExpr = FTI.NoexceptExpr;
4519         }
4520 
4521         S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4522                                       FTI.getExceptionSpecType(),
4523                                       DynamicExceptions,
4524                                       DynamicExceptionRanges,
4525                                       NoexceptExpr,
4526                                       Exceptions,
4527                                       EPI.ExceptionSpec);
4528 
4529         T = Context.getFunctionType(T, ParamTys, EPI);
4530       }
4531       break;
4532     }
4533     case DeclaratorChunk::MemberPointer: {
4534       // The scope spec must refer to a class, or be dependent.
4535       CXXScopeSpec &SS = DeclType.Mem.Scope();
4536       QualType ClsType;
4537 
4538       // Handle pointer nullability.
4539       inferPointerNullability(SimplePointerKind::MemberPointer,
4540                               DeclType.Loc, DeclType.getAttrListRef());
4541 
4542       if (SS.isInvalid()) {
4543         // Avoid emitting extra errors if we already errored on the scope.
4544         D.setInvalidType(true);
4545       } else if (S.isDependentScopeSpecifier(SS) ||
4546                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4547         NestedNameSpecifier *NNS = SS.getScopeRep();
4548         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4549         switch (NNS->getKind()) {
4550         case NestedNameSpecifier::Identifier:
4551           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4552                                                  NNS->getAsIdentifier());
4553           break;
4554 
4555         case NestedNameSpecifier::Namespace:
4556         case NestedNameSpecifier::NamespaceAlias:
4557         case NestedNameSpecifier::Global:
4558         case NestedNameSpecifier::Super:
4559           llvm_unreachable("Nested-name-specifier must name a type");
4560 
4561         case NestedNameSpecifier::TypeSpec:
4562         case NestedNameSpecifier::TypeSpecWithTemplate:
4563           ClsType = QualType(NNS->getAsType(), 0);
4564           // Note: if the NNS has a prefix and ClsType is a nondependent
4565           // TemplateSpecializationType, then the NNS prefix is NOT included
4566           // in ClsType; hence we wrap ClsType into an ElaboratedType.
4567           // NOTE: in particular, no wrap occurs if ClsType already is an
4568           // Elaborated, DependentName, or DependentTemplateSpecialization.
4569           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4570             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4571           break;
4572         }
4573       } else {
4574         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4575              diag::err_illegal_decl_mempointer_in_nonclass)
4576           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4577           << DeclType.Mem.Scope().getRange();
4578         D.setInvalidType(true);
4579       }
4580 
4581       if (!ClsType.isNull())
4582         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4583                                      D.getIdentifier());
4584       if (T.isNull()) {
4585         T = Context.IntTy;
4586         D.setInvalidType(true);
4587       } else if (DeclType.Mem.TypeQuals) {
4588         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4589       }
4590       break;
4591     }
4592 
4593     case DeclaratorChunk::Pipe: {
4594       T = S.BuildReadPipeType(T, DeclType.Loc);
4595       processTypeAttrs(state, T, TAL_DeclSpec,
4596                        D.getDeclSpec().getAttributes().getList());
4597       break;
4598     }
4599     }
4600 
4601     if (T.isNull()) {
4602       D.setInvalidType(true);
4603       T = Context.IntTy;
4604     }
4605 
4606     // See if there are any attributes on this declarator chunk.
4607     processTypeAttrs(state, T, TAL_DeclChunk,
4608                      const_cast<AttributeList *>(DeclType.getAttrs()));
4609   }
4610 
4611   assert(!T.isNull() && "T must not be null after this point");
4612 
4613   if (LangOpts.CPlusPlus && T->isFunctionType()) {
4614     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4615     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4616 
4617     // C++ 8.3.5p4:
4618     //   A cv-qualifier-seq shall only be part of the function type
4619     //   for a nonstatic member function, the function type to which a pointer
4620     //   to member refers, or the top-level function type of a function typedef
4621     //   declaration.
4622     //
4623     // Core issue 547 also allows cv-qualifiers on function types that are
4624     // top-level template type arguments.
4625     bool FreeFunction;
4626     if (!D.getCXXScopeSpec().isSet()) {
4627       FreeFunction = ((D.getContext() != Declarator::MemberContext &&
4628                        D.getContext() != Declarator::LambdaExprContext) ||
4629                       D.getDeclSpec().isFriendSpecified());
4630     } else {
4631       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4632       FreeFunction = (DC && !DC->isRecord());
4633     }
4634 
4635     // C++11 [dcl.fct]p6 (w/DR1417):
4636     // An attempt to specify a function type with a cv-qualifier-seq or a
4637     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4638     //  - the function type for a non-static member function,
4639     //  - the function type to which a pointer to member refers,
4640     //  - the top-level function type of a function typedef declaration or
4641     //    alias-declaration,
4642     //  - the type-id in the default argument of a type-parameter, or
4643     //  - the type-id of a template-argument for a type-parameter
4644     //
4645     // FIXME: Checking this here is insufficient. We accept-invalid on:
4646     //
4647     //   template<typename T> struct S { void f(T); };
4648     //   S<int() const> s;
4649     //
4650     // ... for instance.
4651     if (IsQualifiedFunction &&
4652         !(!FreeFunction &&
4653           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4654         !IsTypedefName &&
4655         D.getContext() != Declarator::TemplateTypeArgContext) {
4656       SourceLocation Loc = D.getLocStart();
4657       SourceRange RemovalRange;
4658       unsigned I;
4659       if (D.isFunctionDeclarator(I)) {
4660         SmallVector<SourceLocation, 4> RemovalLocs;
4661         const DeclaratorChunk &Chunk = D.getTypeObject(I);
4662         assert(Chunk.Kind == DeclaratorChunk::Function);
4663         if (Chunk.Fun.hasRefQualifier())
4664           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4665         if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4666           RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4667         if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4668           RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4669         if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4670           RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4671         if (!RemovalLocs.empty()) {
4672           std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4673                     BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4674           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4675           Loc = RemovalLocs.front();
4676         }
4677       }
4678 
4679       S.Diag(Loc, diag::err_invalid_qualified_function_type)
4680         << FreeFunction << D.isFunctionDeclarator() << T
4681         << getFunctionQualifiersAsString(FnTy)
4682         << FixItHint::CreateRemoval(RemovalRange);
4683 
4684       // Strip the cv-qualifiers and ref-qualifiers from the type.
4685       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4686       EPI.TypeQuals = 0;
4687       EPI.RefQualifier = RQ_None;
4688 
4689       T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4690                                   EPI);
4691       // Rebuild any parens around the identifier in the function type.
4692       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4693         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4694           break;
4695         T = S.BuildParenType(T);
4696       }
4697     }
4698   }
4699 
4700   // Apply any undistributed attributes from the declarator.
4701   processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4702 
4703   // Diagnose any ignored type attributes.
4704   state.diagnoseIgnoredTypeAttrs(T);
4705 
4706   // C++0x [dcl.constexpr]p9:
4707   //  A constexpr specifier used in an object declaration declares the object
4708   //  as const.
4709   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4710     T.addConst();
4711   }
4712 
4713   // If there was an ellipsis in the declarator, the declaration declares a
4714   // parameter pack whose type may be a pack expansion type.
4715   if (D.hasEllipsis()) {
4716     // C++0x [dcl.fct]p13:
4717     //   A declarator-id or abstract-declarator containing an ellipsis shall
4718     //   only be used in a parameter-declaration. Such a parameter-declaration
4719     //   is a parameter pack (14.5.3). [...]
4720     switch (D.getContext()) {
4721     case Declarator::PrototypeContext:
4722     case Declarator::LambdaExprParameterContext:
4723       // C++0x [dcl.fct]p13:
4724       //   [...] When it is part of a parameter-declaration-clause, the
4725       //   parameter pack is a function parameter pack (14.5.3). The type T
4726       //   of the declarator-id of the function parameter pack shall contain
4727       //   a template parameter pack; each template parameter pack in T is
4728       //   expanded by the function parameter pack.
4729       //
4730       // We represent function parameter packs as function parameters whose
4731       // type is a pack expansion.
4732       if (!T->containsUnexpandedParameterPack()) {
4733         S.Diag(D.getEllipsisLoc(),
4734              diag::err_function_parameter_pack_without_parameter_packs)
4735           << T <<  D.getSourceRange();
4736         D.setEllipsisLoc(SourceLocation());
4737       } else {
4738         T = Context.getPackExpansionType(T, None);
4739       }
4740       break;
4741     case Declarator::TemplateParamContext:
4742       // C++0x [temp.param]p15:
4743       //   If a template-parameter is a [...] is a parameter-declaration that
4744       //   declares a parameter pack (8.3.5), then the template-parameter is a
4745       //   template parameter pack (14.5.3).
4746       //
4747       // Note: core issue 778 clarifies that, if there are any unexpanded
4748       // parameter packs in the type of the non-type template parameter, then
4749       // it expands those parameter packs.
4750       if (T->containsUnexpandedParameterPack())
4751         T = Context.getPackExpansionType(T, None);
4752       else
4753         S.Diag(D.getEllipsisLoc(),
4754                LangOpts.CPlusPlus11
4755                  ? diag::warn_cxx98_compat_variadic_templates
4756                  : diag::ext_variadic_templates);
4757       break;
4758 
4759     case Declarator::FileContext:
4760     case Declarator::KNRTypeListContext:
4761     case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
4762     case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
4763     case Declarator::TypeNameContext:
4764     case Declarator::FunctionalCastContext:
4765     case Declarator::CXXNewContext:
4766     case Declarator::AliasDeclContext:
4767     case Declarator::AliasTemplateContext:
4768     case Declarator::MemberContext:
4769     case Declarator::BlockContext:
4770     case Declarator::ForContext:
4771     case Declarator::InitStmtContext:
4772     case Declarator::ConditionContext:
4773     case Declarator::CXXCatchContext:
4774     case Declarator::ObjCCatchContext:
4775     case Declarator::BlockLiteralContext:
4776     case Declarator::LambdaExprContext:
4777     case Declarator::ConversionIdContext:
4778     case Declarator::TrailingReturnContext:
4779     case Declarator::TemplateTypeArgContext:
4780       // FIXME: We may want to allow parameter packs in block-literal contexts
4781       // in the future.
4782       S.Diag(D.getEllipsisLoc(),
4783              diag::err_ellipsis_in_declarator_not_parameter);
4784       D.setEllipsisLoc(SourceLocation());
4785       break;
4786     }
4787   }
4788 
4789   assert(!T.isNull() && "T must not be null at the end of this function");
4790   if (D.isInvalidType())
4791     return Context.getTrivialTypeSourceInfo(T);
4792 
4793   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4794 }
4795 
4796 /// GetTypeForDeclarator - Convert the type for the specified
4797 /// declarator to Type instances.
4798 ///
4799 /// The result of this call will never be null, but the associated
4800 /// type may be a null type if there's an unrecoverable error.
4801 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4802   // Determine the type of the declarator. Not all forms of declarator
4803   // have a type.
4804 
4805   TypeProcessingState state(*this, D);
4806 
4807   TypeSourceInfo *ReturnTypeInfo = nullptr;
4808   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4809 
4810   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4811     inferARCWriteback(state, T);
4812 
4813   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4814 }
4815 
4816 static void transferARCOwnershipToDeclSpec(Sema &S,
4817                                            QualType &declSpecTy,
4818                                            Qualifiers::ObjCLifetime ownership) {
4819   if (declSpecTy->isObjCRetainableType() &&
4820       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4821     Qualifiers qs;
4822     qs.addObjCLifetime(ownership);
4823     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4824   }
4825 }
4826 
4827 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4828                                             Qualifiers::ObjCLifetime ownership,
4829                                             unsigned chunkIndex) {
4830   Sema &S = state.getSema();
4831   Declarator &D = state.getDeclarator();
4832 
4833   // Look for an explicit lifetime attribute.
4834   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4835   for (const AttributeList *attr = chunk.getAttrs(); attr;
4836          attr = attr->getNext())
4837     if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4838       return;
4839 
4840   const char *attrStr = nullptr;
4841   switch (ownership) {
4842   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4843   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4844   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4845   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4846   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4847   }
4848 
4849   IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4850   Arg->Ident = &S.Context.Idents.get(attrStr);
4851   Arg->Loc = SourceLocation();
4852 
4853   ArgsUnion Args(Arg);
4854 
4855   // If there wasn't one, add one (with an invalid source location
4856   // so that we don't make an AttributedType for it).
4857   AttributeList *attr = D.getAttributePool()
4858     .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4859             /*scope*/ nullptr, SourceLocation(),
4860             /*args*/ &Args, 1, AttributeList::AS_GNU);
4861   spliceAttrIntoList(*attr, chunk.getAttrListRef());
4862 
4863   // TODO: mark whether we did this inference?
4864 }
4865 
4866 /// \brief Used for transferring ownership in casts resulting in l-values.
4867 static void transferARCOwnership(TypeProcessingState &state,
4868                                  QualType &declSpecTy,
4869                                  Qualifiers::ObjCLifetime ownership) {
4870   Sema &S = state.getSema();
4871   Declarator &D = state.getDeclarator();
4872 
4873   int inner = -1;
4874   bool hasIndirection = false;
4875   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4876     DeclaratorChunk &chunk = D.getTypeObject(i);
4877     switch (chunk.Kind) {
4878     case DeclaratorChunk::Paren:
4879       // Ignore parens.
4880       break;
4881 
4882     case DeclaratorChunk::Array:
4883     case DeclaratorChunk::Reference:
4884     case DeclaratorChunk::Pointer:
4885       if (inner != -1)
4886         hasIndirection = true;
4887       inner = i;
4888       break;
4889 
4890     case DeclaratorChunk::BlockPointer:
4891       if (inner != -1)
4892         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4893       return;
4894 
4895     case DeclaratorChunk::Function:
4896     case DeclaratorChunk::MemberPointer:
4897     case DeclaratorChunk::Pipe:
4898       return;
4899     }
4900   }
4901 
4902   if (inner == -1)
4903     return;
4904 
4905   DeclaratorChunk &chunk = D.getTypeObject(inner);
4906   if (chunk.Kind == DeclaratorChunk::Pointer) {
4907     if (declSpecTy->isObjCRetainableType())
4908       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4909     if (declSpecTy->isObjCObjectType() && hasIndirection)
4910       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4911   } else {
4912     assert(chunk.Kind == DeclaratorChunk::Array ||
4913            chunk.Kind == DeclaratorChunk::Reference);
4914     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4915   }
4916 }
4917 
4918 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4919   TypeProcessingState state(*this, D);
4920 
4921   TypeSourceInfo *ReturnTypeInfo = nullptr;
4922   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4923 
4924   if (getLangOpts().ObjC1) {
4925     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4926     if (ownership != Qualifiers::OCL_None)
4927       transferARCOwnership(state, declSpecTy, ownership);
4928   }
4929 
4930   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4931 }
4932 
4933 /// Map an AttributedType::Kind to an AttributeList::Kind.
4934 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4935   switch (kind) {
4936   case AttributedType::attr_address_space:
4937     return AttributeList::AT_AddressSpace;
4938   case AttributedType::attr_regparm:
4939     return AttributeList::AT_Regparm;
4940   case AttributedType::attr_vector_size:
4941     return AttributeList::AT_VectorSize;
4942   case AttributedType::attr_neon_vector_type:
4943     return AttributeList::AT_NeonVectorType;
4944   case AttributedType::attr_neon_polyvector_type:
4945     return AttributeList::AT_NeonPolyVectorType;
4946   case AttributedType::attr_objc_gc:
4947     return AttributeList::AT_ObjCGC;
4948   case AttributedType::attr_objc_ownership:
4949   case AttributedType::attr_objc_inert_unsafe_unretained:
4950     return AttributeList::AT_ObjCOwnership;
4951   case AttributedType::attr_noreturn:
4952     return AttributeList::AT_NoReturn;
4953   case AttributedType::attr_cdecl:
4954     return AttributeList::AT_CDecl;
4955   case AttributedType::attr_fastcall:
4956     return AttributeList::AT_FastCall;
4957   case AttributedType::attr_stdcall:
4958     return AttributeList::AT_StdCall;
4959   case AttributedType::attr_thiscall:
4960     return AttributeList::AT_ThisCall;
4961   case AttributedType::attr_regcall:
4962     return AttributeList::AT_RegCall;
4963   case AttributedType::attr_pascal:
4964     return AttributeList::AT_Pascal;
4965   case AttributedType::attr_swiftcall:
4966     return AttributeList::AT_SwiftCall;
4967   case AttributedType::attr_vectorcall:
4968     return AttributeList::AT_VectorCall;
4969   case AttributedType::attr_pcs:
4970   case AttributedType::attr_pcs_vfp:
4971     return AttributeList::AT_Pcs;
4972   case AttributedType::attr_inteloclbicc:
4973     return AttributeList::AT_IntelOclBicc;
4974   case AttributedType::attr_ms_abi:
4975     return AttributeList::AT_MSABI;
4976   case AttributedType::attr_sysv_abi:
4977     return AttributeList::AT_SysVABI;
4978   case AttributedType::attr_preserve_most:
4979     return AttributeList::AT_PreserveMost;
4980   case AttributedType::attr_preserve_all:
4981     return AttributeList::AT_PreserveAll;
4982   case AttributedType::attr_ptr32:
4983     return AttributeList::AT_Ptr32;
4984   case AttributedType::attr_ptr64:
4985     return AttributeList::AT_Ptr64;
4986   case AttributedType::attr_sptr:
4987     return AttributeList::AT_SPtr;
4988   case AttributedType::attr_uptr:
4989     return AttributeList::AT_UPtr;
4990   case AttributedType::attr_nonnull:
4991     return AttributeList::AT_TypeNonNull;
4992   case AttributedType::attr_nullable:
4993     return AttributeList::AT_TypeNullable;
4994   case AttributedType::attr_null_unspecified:
4995     return AttributeList::AT_TypeNullUnspecified;
4996   case AttributedType::attr_objc_kindof:
4997     return AttributeList::AT_ObjCKindOf;
4998   }
4999   llvm_unreachable("unexpected attribute kind!");
5000 }
5001 
5002 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5003                                   const AttributeList *attrs,
5004                                   const AttributeList *DeclAttrs = nullptr) {
5005   // DeclAttrs and attrs cannot be both empty.
5006   assert((attrs || DeclAttrs) &&
5007          "no type attributes in the expected location!");
5008 
5009   AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
5010   // Try to search for an attribute of matching kind in attrs list.
5011   while (attrs && attrs->getKind() != parsedKind)
5012     attrs = attrs->getNext();
5013   if (!attrs) {
5014     // No matching type attribute in attrs list found.
5015     // Try searching through C++11 attributes in the declarator attribute list.
5016     while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
5017                          DeclAttrs->getKind() != parsedKind))
5018       DeclAttrs = DeclAttrs->getNext();
5019     attrs = DeclAttrs;
5020   }
5021 
5022   assert(attrs && "no matching type attribute in expected location!");
5023 
5024   TL.setAttrNameLoc(attrs->getLoc());
5025   if (TL.hasAttrExprOperand()) {
5026     assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
5027     TL.setAttrExprOperand(attrs->getArgAsExpr(0));
5028   } else if (TL.hasAttrEnumOperand()) {
5029     assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
5030            "unexpected attribute operand kind");
5031     if (attrs->isArgIdent(0))
5032       TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
5033     else
5034       TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
5035   }
5036 
5037   // FIXME: preserve this information to here.
5038   if (TL.hasAttrOperand())
5039     TL.setAttrOperandParensRange(SourceRange());
5040 }
5041 
5042 namespace {
5043   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5044     ASTContext &Context;
5045     const DeclSpec &DS;
5046 
5047   public:
5048     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
5049       : Context(Context), DS(DS) {}
5050 
5051     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5052       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
5053       Visit(TL.getModifiedLoc());
5054     }
5055     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5056       Visit(TL.getUnqualifiedLoc());
5057     }
5058     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5059       TL.setNameLoc(DS.getTypeSpecTypeLoc());
5060     }
5061     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5062       TL.setNameLoc(DS.getTypeSpecTypeLoc());
5063       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5064       // addition field. What we have is good enough for dispay of location
5065       // of 'fixit' on interface name.
5066       TL.setNameEndLoc(DS.getLocEnd());
5067     }
5068     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5069       TypeSourceInfo *RepTInfo = nullptr;
5070       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5071       TL.copy(RepTInfo->getTypeLoc());
5072     }
5073     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5074       TypeSourceInfo *RepTInfo = nullptr;
5075       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5076       TL.copy(RepTInfo->getTypeLoc());
5077     }
5078     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5079       TypeSourceInfo *TInfo = nullptr;
5080       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5081 
5082       // If we got no declarator info from previous Sema routines,
5083       // just fill with the typespec loc.
5084       if (!TInfo) {
5085         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5086         return;
5087       }
5088 
5089       TypeLoc OldTL = TInfo->getTypeLoc();
5090       if (TInfo->getType()->getAs<ElaboratedType>()) {
5091         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5092         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5093             .castAs<TemplateSpecializationTypeLoc>();
5094         TL.copy(NamedTL);
5095       } else {
5096         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5097         assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5098       }
5099 
5100     }
5101     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5102       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5103       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5104       TL.setParensRange(DS.getTypeofParensRange());
5105     }
5106     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5107       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5108       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5109       TL.setParensRange(DS.getTypeofParensRange());
5110       assert(DS.getRepAsType());
5111       TypeSourceInfo *TInfo = nullptr;
5112       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5113       TL.setUnderlyingTInfo(TInfo);
5114     }
5115     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5116       // FIXME: This holds only because we only have one unary transform.
5117       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5118       TL.setKWLoc(DS.getTypeSpecTypeLoc());
5119       TL.setParensRange(DS.getTypeofParensRange());
5120       assert(DS.getRepAsType());
5121       TypeSourceInfo *TInfo = nullptr;
5122       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5123       TL.setUnderlyingTInfo(TInfo);
5124     }
5125     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5126       // By default, use the source location of the type specifier.
5127       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5128       if (TL.needsExtraLocalData()) {
5129         // Set info for the written builtin specifiers.
5130         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5131         // Try to have a meaningful source location.
5132         if (TL.getWrittenSignSpec() != TSS_unspecified)
5133           TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5134         if (TL.getWrittenWidthSpec() != TSW_unspecified)
5135           TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5136       }
5137     }
5138     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5139       ElaboratedTypeKeyword Keyword
5140         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5141       if (DS.getTypeSpecType() == TST_typename) {
5142         TypeSourceInfo *TInfo = nullptr;
5143         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5144         if (TInfo) {
5145           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5146           return;
5147         }
5148       }
5149       TL.setElaboratedKeywordLoc(Keyword != ETK_None
5150                                  ? DS.getTypeSpecTypeLoc()
5151                                  : SourceLocation());
5152       const CXXScopeSpec& SS = DS.getTypeSpecScope();
5153       TL.setQualifierLoc(SS.getWithLocInContext(Context));
5154       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5155     }
5156     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5157       assert(DS.getTypeSpecType() == TST_typename);
5158       TypeSourceInfo *TInfo = nullptr;
5159       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5160       assert(TInfo);
5161       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5162     }
5163     void VisitDependentTemplateSpecializationTypeLoc(
5164                                  DependentTemplateSpecializationTypeLoc TL) {
5165       assert(DS.getTypeSpecType() == TST_typename);
5166       TypeSourceInfo *TInfo = nullptr;
5167       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5168       assert(TInfo);
5169       TL.copy(
5170           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5171     }
5172     void VisitTagTypeLoc(TagTypeLoc TL) {
5173       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5174     }
5175     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5176       // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5177       // or an _Atomic qualifier.
5178       if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5179         TL.setKWLoc(DS.getTypeSpecTypeLoc());
5180         TL.setParensRange(DS.getTypeofParensRange());
5181 
5182         TypeSourceInfo *TInfo = nullptr;
5183         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5184         assert(TInfo);
5185         TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5186       } else {
5187         TL.setKWLoc(DS.getAtomicSpecLoc());
5188         // No parens, to indicate this was spelled as an _Atomic qualifier.
5189         TL.setParensRange(SourceRange());
5190         Visit(TL.getValueLoc());
5191       }
5192     }
5193 
5194     void VisitPipeTypeLoc(PipeTypeLoc TL) {
5195       TL.setKWLoc(DS.getTypeSpecTypeLoc());
5196 
5197       TypeSourceInfo *TInfo = nullptr;
5198       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5199       TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5200     }
5201 
5202     void VisitTypeLoc(TypeLoc TL) {
5203       // FIXME: add other typespec types and change this to an assert.
5204       TL.initialize(Context, DS.getTypeSpecTypeLoc());
5205     }
5206   };
5207 
5208   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5209     ASTContext &Context;
5210     const DeclaratorChunk &Chunk;
5211 
5212   public:
5213     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
5214       : Context(Context), Chunk(Chunk) {}
5215 
5216     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5217       llvm_unreachable("qualified type locs not expected here!");
5218     }
5219     void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5220       llvm_unreachable("decayed type locs not expected here!");
5221     }
5222 
5223     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5224       fillAttributedTypeLoc(TL, Chunk.getAttrs());
5225     }
5226     void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5227       // nothing
5228     }
5229     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5230       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5231       TL.setCaretLoc(Chunk.Loc);
5232     }
5233     void VisitPointerTypeLoc(PointerTypeLoc TL) {
5234       assert(Chunk.Kind == DeclaratorChunk::Pointer);
5235       TL.setStarLoc(Chunk.Loc);
5236     }
5237     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5238       assert(Chunk.Kind == DeclaratorChunk::Pointer);
5239       TL.setStarLoc(Chunk.Loc);
5240     }
5241     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5242       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5243       const CXXScopeSpec& SS = Chunk.Mem.Scope();
5244       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5245 
5246       const Type* ClsTy = TL.getClass();
5247       QualType ClsQT = QualType(ClsTy, 0);
5248       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5249       // Now copy source location info into the type loc component.
5250       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5251       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5252       case NestedNameSpecifier::Identifier:
5253         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5254         {
5255           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5256           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5257           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5258           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5259         }
5260         break;
5261 
5262       case NestedNameSpecifier::TypeSpec:
5263       case NestedNameSpecifier::TypeSpecWithTemplate:
5264         if (isa<ElaboratedType>(ClsTy)) {
5265           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5266           ETLoc.setElaboratedKeywordLoc(SourceLocation());
5267           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5268           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5269           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5270         } else {
5271           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5272         }
5273         break;
5274 
5275       case NestedNameSpecifier::Namespace:
5276       case NestedNameSpecifier::NamespaceAlias:
5277       case NestedNameSpecifier::Global:
5278       case NestedNameSpecifier::Super:
5279         llvm_unreachable("Nested-name-specifier must name a type");
5280       }
5281 
5282       // Finally fill in MemberPointerLocInfo fields.
5283       TL.setStarLoc(Chunk.Loc);
5284       TL.setClassTInfo(ClsTInfo);
5285     }
5286     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5287       assert(Chunk.Kind == DeclaratorChunk::Reference);
5288       // 'Amp' is misleading: this might have been originally
5289       /// spelled with AmpAmp.
5290       TL.setAmpLoc(Chunk.Loc);
5291     }
5292     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5293       assert(Chunk.Kind == DeclaratorChunk::Reference);
5294       assert(!Chunk.Ref.LValueRef);
5295       TL.setAmpAmpLoc(Chunk.Loc);
5296     }
5297     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5298       assert(Chunk.Kind == DeclaratorChunk::Array);
5299       TL.setLBracketLoc(Chunk.Loc);
5300       TL.setRBracketLoc(Chunk.EndLoc);
5301       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5302     }
5303     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5304       assert(Chunk.Kind == DeclaratorChunk::Function);
5305       TL.setLocalRangeBegin(Chunk.Loc);
5306       TL.setLocalRangeEnd(Chunk.EndLoc);
5307 
5308       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5309       TL.setLParenLoc(FTI.getLParenLoc());
5310       TL.setRParenLoc(FTI.getRParenLoc());
5311       for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5312         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5313         TL.setParam(tpi++, Param);
5314       }
5315       TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
5316     }
5317     void VisitParenTypeLoc(ParenTypeLoc TL) {
5318       assert(Chunk.Kind == DeclaratorChunk::Paren);
5319       TL.setLParenLoc(Chunk.Loc);
5320       TL.setRParenLoc(Chunk.EndLoc);
5321     }
5322     void VisitPipeTypeLoc(PipeTypeLoc TL) {
5323       assert(Chunk.Kind == DeclaratorChunk::Pipe);
5324       TL.setKWLoc(Chunk.Loc);
5325     }
5326 
5327     void VisitTypeLoc(TypeLoc TL) {
5328       llvm_unreachable("unsupported TypeLoc kind in declarator!");
5329     }
5330   };
5331 } // end anonymous namespace
5332 
5333 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5334   SourceLocation Loc;
5335   switch (Chunk.Kind) {
5336   case DeclaratorChunk::Function:
5337   case DeclaratorChunk::Array:
5338   case DeclaratorChunk::Paren:
5339   case DeclaratorChunk::Pipe:
5340     llvm_unreachable("cannot be _Atomic qualified");
5341 
5342   case DeclaratorChunk::Pointer:
5343     Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5344     break;
5345 
5346   case DeclaratorChunk::BlockPointer:
5347   case DeclaratorChunk::Reference:
5348   case DeclaratorChunk::MemberPointer:
5349     // FIXME: Provide a source location for the _Atomic keyword.
5350     break;
5351   }
5352 
5353   ATL.setKWLoc(Loc);
5354   ATL.setParensRange(SourceRange());
5355 }
5356 
5357 /// \brief Create and instantiate a TypeSourceInfo with type source information.
5358 ///
5359 /// \param T QualType referring to the type as written in source code.
5360 ///
5361 /// \param ReturnTypeInfo For declarators whose return type does not show
5362 /// up in the normal place in the declaration specifiers (such as a C++
5363 /// conversion function), this pointer will refer to a type source information
5364 /// for that return type.
5365 TypeSourceInfo *
5366 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
5367                                      TypeSourceInfo *ReturnTypeInfo) {
5368   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
5369   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5370   const AttributeList *DeclAttrs = D.getAttributes();
5371 
5372   // Handle parameter packs whose type is a pack expansion.
5373   if (isa<PackExpansionType>(T)) {
5374     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5375     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5376   }
5377 
5378   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5379     // An AtomicTypeLoc might be produced by an atomic qualifier in this
5380     // declarator chunk.
5381     if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5382       fillAtomicQualLoc(ATL, D.getTypeObject(i));
5383       CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5384     }
5385 
5386     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5387       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
5388       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5389     }
5390 
5391     // FIXME: Ordering here?
5392     while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5393       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5394 
5395     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
5396     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5397   }
5398 
5399   // If we have different source information for the return type, use
5400   // that.  This really only applies to C++ conversion functions.
5401   if (ReturnTypeInfo) {
5402     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5403     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5404     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5405   } else {
5406     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
5407   }
5408 
5409   return TInfo;
5410 }
5411 
5412 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5413 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5414   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5415   // and Sema during declaration parsing. Try deallocating/caching them when
5416   // it's appropriate, instead of allocating them and keeping them around.
5417   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5418                                                        TypeAlignment);
5419   new (LocT) LocInfoType(T, TInfo);
5420   assert(LocT->getTypeClass() != T->getTypeClass() &&
5421          "LocInfoType's TypeClass conflicts with an existing Type class");
5422   return ParsedType::make(QualType(LocT, 0));
5423 }
5424 
5425 void LocInfoType::getAsStringInternal(std::string &Str,
5426                                       const PrintingPolicy &Policy) const {
5427   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5428          " was used directly instead of getting the QualType through"
5429          " GetTypeFromParser");
5430 }
5431 
5432 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5433   // C99 6.7.6: Type names have no identifier.  This is already validated by
5434   // the parser.
5435   assert(D.getIdentifier() == nullptr &&
5436          "Type name should have no identifier!");
5437 
5438   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5439   QualType T = TInfo->getType();
5440   if (D.isInvalidType())
5441     return true;
5442 
5443   // Make sure there are no unused decl attributes on the declarator.
5444   // We don't want to do this for ObjC parameters because we're going
5445   // to apply them to the actual parameter declaration.
5446   // Likewise, we don't want to do this for alias declarations, because
5447   // we are actually going to build a declaration from this eventually.
5448   if (D.getContext() != Declarator::ObjCParameterContext &&
5449       D.getContext() != Declarator::AliasDeclContext &&
5450       D.getContext() != Declarator::AliasTemplateContext)
5451     checkUnusedDeclAttributes(D);
5452 
5453   if (getLangOpts().CPlusPlus) {
5454     // Check that there are no default arguments (C++ only).
5455     CheckExtraCXXDefaultArguments(D);
5456   }
5457 
5458   return CreateParsedType(T, TInfo);
5459 }
5460 
5461 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5462   QualType T = Context.getObjCInstanceType();
5463   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5464   return CreateParsedType(T, TInfo);
5465 }
5466 
5467 //===----------------------------------------------------------------------===//
5468 // Type Attribute Processing
5469 //===----------------------------------------------------------------------===//
5470 
5471 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5472 /// specified type.  The attribute contains 1 argument, the id of the address
5473 /// space for the type.
5474 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5475                                             const AttributeList &Attr, Sema &S){
5476 
5477   // If this type is already address space qualified, reject it.
5478   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5479   // qualifiers for two or more different address spaces."
5480   if (Type.getAddressSpace()) {
5481     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5482     Attr.setInvalid();
5483     return;
5484   }
5485 
5486   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5487   // qualified by an address-space qualifier."
5488   if (Type->isFunctionType()) {
5489     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5490     Attr.setInvalid();
5491     return;
5492   }
5493 
5494   unsigned ASIdx;
5495   if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5496     // Check the attribute arguments.
5497     if (Attr.getNumArgs() != 1) {
5498       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5499         << Attr.getName() << 1;
5500       Attr.setInvalid();
5501       return;
5502     }
5503     Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5504     llvm::APSInt addrSpace(32);
5505     if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
5506         !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
5507       S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5508         << Attr.getName() << AANT_ArgumentIntegerConstant
5509         << ASArgExpr->getSourceRange();
5510       Attr.setInvalid();
5511       return;
5512     }
5513 
5514     // Bounds checking.
5515     if (addrSpace.isSigned()) {
5516       if (addrSpace.isNegative()) {
5517         S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
5518           << ASArgExpr->getSourceRange();
5519         Attr.setInvalid();
5520         return;
5521       }
5522       addrSpace.setIsSigned(false);
5523     }
5524     llvm::APSInt max(addrSpace.getBitWidth());
5525     max = Qualifiers::MaxAddressSpace;
5526     if (addrSpace > max) {
5527       S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
5528         << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
5529       Attr.setInvalid();
5530       return;
5531     }
5532     ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
5533   } else {
5534     // The keyword-based type attributes imply which address space to use.
5535     switch (Attr.getKind()) {
5536     case AttributeList::AT_OpenCLGlobalAddressSpace:
5537       ASIdx = LangAS::opencl_global; break;
5538     case AttributeList::AT_OpenCLLocalAddressSpace:
5539       ASIdx = LangAS::opencl_local; break;
5540     case AttributeList::AT_OpenCLConstantAddressSpace:
5541       ASIdx = LangAS::opencl_constant; break;
5542     case AttributeList::AT_OpenCLGenericAddressSpace:
5543       ASIdx = LangAS::opencl_generic; break;
5544     default:
5545       assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5546       ASIdx = 0; break;
5547     }
5548   }
5549 
5550   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5551 }
5552 
5553 /// Does this type have a "direct" ownership qualifier?  That is,
5554 /// is it written like "__strong id", as opposed to something like
5555 /// "typeof(foo)", where that happens to be strong?
5556 static bool hasDirectOwnershipQualifier(QualType type) {
5557   // Fast path: no qualifier at all.
5558   assert(type.getQualifiers().hasObjCLifetime());
5559 
5560   while (true) {
5561     // __strong id
5562     if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5563       if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5564         return true;
5565 
5566       type = attr->getModifiedType();
5567 
5568     // X *__strong (...)
5569     } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5570       type = paren->getInnerType();
5571 
5572     // That's it for things we want to complain about.  In particular,
5573     // we do not want to look through typedefs, typeof(expr),
5574     // typeof(type), or any other way that the type is somehow
5575     // abstracted.
5576     } else {
5577 
5578       return false;
5579     }
5580   }
5581 }
5582 
5583 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5584 /// attribute on the specified type.
5585 ///
5586 /// Returns 'true' if the attribute was handled.
5587 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5588                                        AttributeList &attr,
5589                                        QualType &type) {
5590   bool NonObjCPointer = false;
5591 
5592   if (!type->isDependentType() && !type->isUndeducedType()) {
5593     if (const PointerType *ptr = type->getAs<PointerType>()) {
5594       QualType pointee = ptr->getPointeeType();
5595       if (pointee->isObjCRetainableType() || pointee->isPointerType())
5596         return false;
5597       // It is important not to lose the source info that there was an attribute
5598       // applied to non-objc pointer. We will create an attributed type but
5599       // its type will be the same as the original type.
5600       NonObjCPointer = true;
5601     } else if (!type->isObjCRetainableType()) {
5602       return false;
5603     }
5604 
5605     // Don't accept an ownership attribute in the declspec if it would
5606     // just be the return type of a block pointer.
5607     if (state.isProcessingDeclSpec()) {
5608       Declarator &D = state.getDeclarator();
5609       if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5610                                   /*onlyBlockPointers=*/true))
5611         return false;
5612     }
5613   }
5614 
5615   Sema &S = state.getSema();
5616   SourceLocation AttrLoc = attr.getLoc();
5617   if (AttrLoc.isMacroID())
5618     AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5619 
5620   if (!attr.isArgIdent(0)) {
5621     S.Diag(AttrLoc, diag::err_attribute_argument_type)
5622       << attr.getName() << AANT_ArgumentString;
5623     attr.setInvalid();
5624     return true;
5625   }
5626 
5627   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5628   Qualifiers::ObjCLifetime lifetime;
5629   if (II->isStr("none"))
5630     lifetime = Qualifiers::OCL_ExplicitNone;
5631   else if (II->isStr("strong"))
5632     lifetime = Qualifiers::OCL_Strong;
5633   else if (II->isStr("weak"))
5634     lifetime = Qualifiers::OCL_Weak;
5635   else if (II->isStr("autoreleasing"))
5636     lifetime = Qualifiers::OCL_Autoreleasing;
5637   else {
5638     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5639       << attr.getName() << II;
5640     attr.setInvalid();
5641     return true;
5642   }
5643 
5644   // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5645   // outside of ARC mode.
5646   if (!S.getLangOpts().ObjCAutoRefCount &&
5647       lifetime != Qualifiers::OCL_Weak &&
5648       lifetime != Qualifiers::OCL_ExplicitNone) {
5649     return true;
5650   }
5651 
5652   SplitQualType underlyingType = type.split();
5653 
5654   // Check for redundant/conflicting ownership qualifiers.
5655   if (Qualifiers::ObjCLifetime previousLifetime
5656         = type.getQualifiers().getObjCLifetime()) {
5657     // If it's written directly, that's an error.
5658     if (hasDirectOwnershipQualifier(type)) {
5659       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5660         << type;
5661       return true;
5662     }
5663 
5664     // Otherwise, if the qualifiers actually conflict, pull sugar off
5665     // and remove the ObjCLifetime qualifiers.
5666     if (previousLifetime != lifetime) {
5667       // It's possible to have multiple local ObjCLifetime qualifiers. We
5668       // can't stop after we reach a type that is directly qualified.
5669       const Type *prevTy = nullptr;
5670       while (!prevTy || prevTy != underlyingType.Ty) {
5671         prevTy = underlyingType.Ty;
5672         underlyingType = underlyingType.getSingleStepDesugaredType();
5673       }
5674       underlyingType.Quals.removeObjCLifetime();
5675     }
5676   }
5677 
5678   underlyingType.Quals.addObjCLifetime(lifetime);
5679 
5680   if (NonObjCPointer) {
5681     StringRef name = attr.getName()->getName();
5682     switch (lifetime) {
5683     case Qualifiers::OCL_None:
5684     case Qualifiers::OCL_ExplicitNone:
5685       break;
5686     case Qualifiers::OCL_Strong: name = "__strong"; break;
5687     case Qualifiers::OCL_Weak: name = "__weak"; break;
5688     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5689     }
5690     S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5691       << TDS_ObjCObjOrBlock << type;
5692   }
5693 
5694   // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
5695   // because having both 'T' and '__unsafe_unretained T' exist in the type
5696   // system causes unfortunate widespread consistency problems.  (For example,
5697   // they're not considered compatible types, and we mangle them identicially
5698   // as template arguments.)  These problems are all individually fixable,
5699   // but it's easier to just not add the qualifier and instead sniff it out
5700   // in specific places using isObjCInertUnsafeUnretainedType().
5701   //
5702   // Doing this does means we miss some trivial consistency checks that
5703   // would've triggered in ARC, but that's better than trying to solve all
5704   // the coexistence problems with __unsafe_unretained.
5705   if (!S.getLangOpts().ObjCAutoRefCount &&
5706       lifetime == Qualifiers::OCL_ExplicitNone) {
5707     type = S.Context.getAttributedType(
5708                              AttributedType::attr_objc_inert_unsafe_unretained,
5709                                        type, type);
5710     return true;
5711   }
5712 
5713   QualType origType = type;
5714   if (!NonObjCPointer)
5715     type = S.Context.getQualifiedType(underlyingType);
5716 
5717   // If we have a valid source location for the attribute, use an
5718   // AttributedType instead.
5719   if (AttrLoc.isValid())
5720     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5721                                        origType, type);
5722 
5723   auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5724                             unsigned diagnostic, QualType type) {
5725     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5726       S.DelayedDiagnostics.add(
5727           sema::DelayedDiagnostic::makeForbiddenType(
5728               S.getSourceManager().getExpansionLoc(loc),
5729               diagnostic, type, /*ignored*/ 0));
5730     } else {
5731       S.Diag(loc, diagnostic);
5732     }
5733   };
5734 
5735   // Sometimes, __weak isn't allowed.
5736   if (lifetime == Qualifiers::OCL_Weak &&
5737       !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5738 
5739     // Use a specialized diagnostic if the runtime just doesn't support them.
5740     unsigned diagnostic =
5741       (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5742                                        : diag::err_arc_weak_no_runtime);
5743 
5744     // In any case, delay the diagnostic until we know what we're parsing.
5745     diagnoseOrDelay(S, AttrLoc, diagnostic, type);
5746 
5747     attr.setInvalid();
5748     return true;
5749   }
5750 
5751   // Forbid __weak for class objects marked as
5752   // objc_arc_weak_reference_unavailable
5753   if (lifetime == Qualifiers::OCL_Weak) {
5754     if (const ObjCObjectPointerType *ObjT =
5755           type->getAs<ObjCObjectPointerType>()) {
5756       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5757         if (Class->isArcWeakrefUnavailable()) {
5758           S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5759           S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5760                  diag::note_class_declared);
5761         }
5762       }
5763     }
5764   }
5765 
5766   return true;
5767 }
5768 
5769 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5770 /// attribute on the specified type.  Returns true to indicate that
5771 /// the attribute was handled, false to indicate that the type does
5772 /// not permit the attribute.
5773 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5774                                  AttributeList &attr,
5775                                  QualType &type) {
5776   Sema &S = state.getSema();
5777 
5778   // Delay if this isn't some kind of pointer.
5779   if (!type->isPointerType() &&
5780       !type->isObjCObjectPointerType() &&
5781       !type->isBlockPointerType())
5782     return false;
5783 
5784   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5785     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5786     attr.setInvalid();
5787     return true;
5788   }
5789 
5790   // Check the attribute arguments.
5791   if (!attr.isArgIdent(0)) {
5792     S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5793       << attr.getName() << AANT_ArgumentString;
5794     attr.setInvalid();
5795     return true;
5796   }
5797   Qualifiers::GC GCAttr;
5798   if (attr.getNumArgs() > 1) {
5799     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5800       << attr.getName() << 1;
5801     attr.setInvalid();
5802     return true;
5803   }
5804 
5805   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5806   if (II->isStr("weak"))
5807     GCAttr = Qualifiers::Weak;
5808   else if (II->isStr("strong"))
5809     GCAttr = Qualifiers::Strong;
5810   else {
5811     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5812       << attr.getName() << II;
5813     attr.setInvalid();
5814     return true;
5815   }
5816 
5817   QualType origType = type;
5818   type = S.Context.getObjCGCQualType(origType, GCAttr);
5819 
5820   // Make an attributed type to preserve the source information.
5821   if (attr.getLoc().isValid())
5822     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5823                                        origType, type);
5824 
5825   return true;
5826 }
5827 
5828 namespace {
5829   /// A helper class to unwrap a type down to a function for the
5830   /// purposes of applying attributes there.
5831   ///
5832   /// Use:
5833   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
5834   ///   if (unwrapped.isFunctionType()) {
5835   ///     const FunctionType *fn = unwrapped.get();
5836   ///     // change fn somehow
5837   ///     T = unwrapped.wrap(fn);
5838   ///   }
5839   struct FunctionTypeUnwrapper {
5840     enum WrapKind {
5841       Desugar,
5842       Attributed,
5843       Parens,
5844       Pointer,
5845       BlockPointer,
5846       Reference,
5847       MemberPointer
5848     };
5849 
5850     QualType Original;
5851     const FunctionType *Fn;
5852     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5853 
5854     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5855       while (true) {
5856         const Type *Ty = T.getTypePtr();
5857         if (isa<FunctionType>(Ty)) {
5858           Fn = cast<FunctionType>(Ty);
5859           return;
5860         } else if (isa<ParenType>(Ty)) {
5861           T = cast<ParenType>(Ty)->getInnerType();
5862           Stack.push_back(Parens);
5863         } else if (isa<PointerType>(Ty)) {
5864           T = cast<PointerType>(Ty)->getPointeeType();
5865           Stack.push_back(Pointer);
5866         } else if (isa<BlockPointerType>(Ty)) {
5867           T = cast<BlockPointerType>(Ty)->getPointeeType();
5868           Stack.push_back(BlockPointer);
5869         } else if (isa<MemberPointerType>(Ty)) {
5870           T = cast<MemberPointerType>(Ty)->getPointeeType();
5871           Stack.push_back(MemberPointer);
5872         } else if (isa<ReferenceType>(Ty)) {
5873           T = cast<ReferenceType>(Ty)->getPointeeType();
5874           Stack.push_back(Reference);
5875         } else if (isa<AttributedType>(Ty)) {
5876           T = cast<AttributedType>(Ty)->getEquivalentType();
5877           Stack.push_back(Attributed);
5878         } else {
5879           const Type *DTy = Ty->getUnqualifiedDesugaredType();
5880           if (Ty == DTy) {
5881             Fn = nullptr;
5882             return;
5883           }
5884 
5885           T = QualType(DTy, 0);
5886           Stack.push_back(Desugar);
5887         }
5888       }
5889     }
5890 
5891     bool isFunctionType() const { return (Fn != nullptr); }
5892     const FunctionType *get() const { return Fn; }
5893 
5894     QualType wrap(Sema &S, const FunctionType *New) {
5895       // If T wasn't modified from the unwrapped type, do nothing.
5896       if (New == get()) return Original;
5897 
5898       Fn = New;
5899       return wrap(S.Context, Original, 0);
5900     }
5901 
5902   private:
5903     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5904       if (I == Stack.size())
5905         return C.getQualifiedType(Fn, Old.getQualifiers());
5906 
5907       // Build up the inner type, applying the qualifiers from the old
5908       // type to the new type.
5909       SplitQualType SplitOld = Old.split();
5910 
5911       // As a special case, tail-recurse if there are no qualifiers.
5912       if (SplitOld.Quals.empty())
5913         return wrap(C, SplitOld.Ty, I);
5914       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5915     }
5916 
5917     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5918       if (I == Stack.size()) return QualType(Fn, 0);
5919 
5920       switch (static_cast<WrapKind>(Stack[I++])) {
5921       case Desugar:
5922         // This is the point at which we potentially lose source
5923         // information.
5924         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5925 
5926       case Attributed:
5927         return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
5928 
5929       case Parens: {
5930         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5931         return C.getParenType(New);
5932       }
5933 
5934       case Pointer: {
5935         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5936         return C.getPointerType(New);
5937       }
5938 
5939       case BlockPointer: {
5940         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5941         return C.getBlockPointerType(New);
5942       }
5943 
5944       case MemberPointer: {
5945         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5946         QualType New = wrap(C, OldMPT->getPointeeType(), I);
5947         return C.getMemberPointerType(New, OldMPT->getClass());
5948       }
5949 
5950       case Reference: {
5951         const ReferenceType *OldRef = cast<ReferenceType>(Old);
5952         QualType New = wrap(C, OldRef->getPointeeType(), I);
5953         if (isa<LValueReferenceType>(OldRef))
5954           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5955         else
5956           return C.getRValueReferenceType(New);
5957       }
5958       }
5959 
5960       llvm_unreachable("unknown wrapping kind");
5961     }
5962   };
5963 } // end anonymous namespace
5964 
5965 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5966                                              AttributeList &Attr,
5967                                              QualType &Type) {
5968   Sema &S = State.getSema();
5969 
5970   AttributeList::Kind Kind = Attr.getKind();
5971   QualType Desugared = Type;
5972   const AttributedType *AT = dyn_cast<AttributedType>(Type);
5973   while (AT) {
5974     AttributedType::Kind CurAttrKind = AT->getAttrKind();
5975 
5976     // You cannot specify duplicate type attributes, so if the attribute has
5977     // already been applied, flag it.
5978     if (getAttrListKind(CurAttrKind) == Kind) {
5979       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5980         << Attr.getName();
5981       return true;
5982     }
5983 
5984     // You cannot have both __sptr and __uptr on the same type, nor can you
5985     // have __ptr32 and __ptr64.
5986     if ((CurAttrKind == AttributedType::attr_ptr32 &&
5987          Kind == AttributeList::AT_Ptr64) ||
5988         (CurAttrKind == AttributedType::attr_ptr64 &&
5989          Kind == AttributeList::AT_Ptr32)) {
5990       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5991         << "'__ptr32'" << "'__ptr64'";
5992       return true;
5993     } else if ((CurAttrKind == AttributedType::attr_sptr &&
5994                 Kind == AttributeList::AT_UPtr) ||
5995                (CurAttrKind == AttributedType::attr_uptr &&
5996                 Kind == AttributeList::AT_SPtr)) {
5997       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5998         << "'__sptr'" << "'__uptr'";
5999       return true;
6000     }
6001 
6002     Desugared = AT->getEquivalentType();
6003     AT = dyn_cast<AttributedType>(Desugared);
6004   }
6005 
6006   // Pointer type qualifiers can only operate on pointer types, but not
6007   // pointer-to-member types.
6008   if (!isa<PointerType>(Desugared)) {
6009     if (Type->isMemberPointerType())
6010       S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
6011           << Attr.getName();
6012     else
6013       S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
6014           << Attr.getName() << 0;
6015     return true;
6016   }
6017 
6018   AttributedType::Kind TAK;
6019   switch (Kind) {
6020   default: llvm_unreachable("Unknown attribute kind");
6021   case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
6022   case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
6023   case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
6024   case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
6025   }
6026 
6027   Type = S.Context.getAttributedType(TAK, Type, Type);
6028   return false;
6029 }
6030 
6031 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
6032                                          NullabilityKind nullability,
6033                                          SourceLocation nullabilityLoc,
6034                                          bool isContextSensitive,
6035                                          bool allowOnArrayType) {
6036   recordNullabilitySeen(*this, nullabilityLoc);
6037 
6038   // Check for existing nullability attributes on the type.
6039   QualType desugared = type;
6040   while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6041     // Check whether there is already a null
6042     if (auto existingNullability = attributed->getImmediateNullability()) {
6043       // Duplicated nullability.
6044       if (nullability == *existingNullability) {
6045         Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6046           << DiagNullabilityKind(nullability, isContextSensitive)
6047           << FixItHint::CreateRemoval(nullabilityLoc);
6048 
6049         break;
6050       }
6051 
6052       // Conflicting nullability.
6053       Diag(nullabilityLoc, diag::err_nullability_conflicting)
6054         << DiagNullabilityKind(nullability, isContextSensitive)
6055         << DiagNullabilityKind(*existingNullability, false);
6056       return true;
6057     }
6058 
6059     desugared = attributed->getModifiedType();
6060   }
6061 
6062   // If there is already a different nullability specifier, complain.
6063   // This (unlike the code above) looks through typedefs that might
6064   // have nullability specifiers on them, which means we cannot
6065   // provide a useful Fix-It.
6066   if (auto existingNullability = desugared->getNullability(Context)) {
6067     if (nullability != *existingNullability) {
6068       Diag(nullabilityLoc, diag::err_nullability_conflicting)
6069         << DiagNullabilityKind(nullability, isContextSensitive)
6070         << DiagNullabilityKind(*existingNullability, false);
6071 
6072       // Try to find the typedef with the existing nullability specifier.
6073       if (auto typedefType = desugared->getAs<TypedefType>()) {
6074         TypedefNameDecl *typedefDecl = typedefType->getDecl();
6075         QualType underlyingType = typedefDecl->getUnderlyingType();
6076         if (auto typedefNullability
6077               = AttributedType::stripOuterNullability(underlyingType)) {
6078           if (*typedefNullability == *existingNullability) {
6079             Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6080               << DiagNullabilityKind(*existingNullability, false);
6081           }
6082         }
6083       }
6084 
6085       return true;
6086     }
6087   }
6088 
6089   // If this definitely isn't a pointer type, reject the specifier.
6090   if (!desugared->canHaveNullability() &&
6091       !(allowOnArrayType && desugared->isArrayType())) {
6092     Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6093       << DiagNullabilityKind(nullability, isContextSensitive) << type;
6094     return true;
6095   }
6096 
6097   // For the context-sensitive keywords/Objective-C property
6098   // attributes, require that the type be a single-level pointer.
6099   if (isContextSensitive) {
6100     // Make sure that the pointee isn't itself a pointer type.
6101     const Type *pointeeType;
6102     if (desugared->isArrayType())
6103       pointeeType = desugared->getArrayElementTypeNoTypeQual();
6104     else
6105       pointeeType = desugared->getPointeeType().getTypePtr();
6106 
6107     if (pointeeType->isAnyPointerType() ||
6108         pointeeType->isObjCObjectPointerType() ||
6109         pointeeType->isMemberPointerType()) {
6110       Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6111         << DiagNullabilityKind(nullability, true)
6112         << type;
6113       Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6114         << DiagNullabilityKind(nullability, false)
6115         << type
6116         << FixItHint::CreateReplacement(nullabilityLoc,
6117                                         getNullabilitySpelling(nullability));
6118       return true;
6119     }
6120   }
6121 
6122   // Form the attributed type.
6123   type = Context.getAttributedType(
6124            AttributedType::getNullabilityAttrKind(nullability), type, type);
6125   return false;
6126 }
6127 
6128 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
6129   if (isa<ObjCTypeParamType>(type)) {
6130     // Build the attributed type to record where __kindof occurred.
6131     type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6132                                      type, type);
6133     return false;
6134   }
6135 
6136   // Find out if it's an Objective-C object or object pointer type;
6137   const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6138   const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6139                                           : type->getAs<ObjCObjectType>();
6140 
6141   // If not, we can't apply __kindof.
6142   if (!objType) {
6143     // FIXME: Handle dependent types that aren't yet object types.
6144     Diag(loc, diag::err_objc_kindof_nonobject)
6145       << type;
6146     return true;
6147   }
6148 
6149   // Rebuild the "equivalent" type, which pushes __kindof down into
6150   // the object type.
6151   // There is no need to apply kindof on an unqualified id type.
6152   QualType equivType = Context.getObjCObjectType(
6153       objType->getBaseType(), objType->getTypeArgsAsWritten(),
6154       objType->getProtocols(),
6155       /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6156 
6157   // If we started with an object pointer type, rebuild it.
6158   if (ptrType) {
6159     equivType = Context.getObjCObjectPointerType(equivType);
6160     if (auto nullability = type->getNullability(Context)) {
6161       auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
6162       equivType = Context.getAttributedType(attrKind, equivType, equivType);
6163     }
6164   }
6165 
6166   // Build the attributed type to record where __kindof occurred.
6167   type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6168                                    type,
6169                                    equivType);
6170 
6171   return false;
6172 }
6173 
6174 /// Map a nullability attribute kind to a nullability kind.
6175 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
6176   switch (kind) {
6177   case AttributeList::AT_TypeNonNull:
6178     return NullabilityKind::NonNull;
6179 
6180   case AttributeList::AT_TypeNullable:
6181     return NullabilityKind::Nullable;
6182 
6183   case AttributeList::AT_TypeNullUnspecified:
6184     return NullabilityKind::Unspecified;
6185 
6186   default:
6187     llvm_unreachable("not a nullability attribute kind");
6188   }
6189 }
6190 
6191 /// Distribute a nullability type attribute that cannot be applied to
6192 /// the type specifier to a pointer, block pointer, or member pointer
6193 /// declarator, complaining if necessary.
6194 ///
6195 /// \returns true if the nullability annotation was distributed, false
6196 /// otherwise.
6197 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6198                                           QualType type,
6199                                           AttributeList &attr) {
6200   Declarator &declarator = state.getDeclarator();
6201 
6202   /// Attempt to move the attribute to the specified chunk.
6203   auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6204     // If there is already a nullability attribute there, don't add
6205     // one.
6206     if (hasNullabilityAttr(chunk.getAttrListRef()))
6207       return false;
6208 
6209     // Complain about the nullability qualifier being in the wrong
6210     // place.
6211     enum {
6212       PK_Pointer,
6213       PK_BlockPointer,
6214       PK_MemberPointer,
6215       PK_FunctionPointer,
6216       PK_MemberFunctionPointer,
6217     } pointerKind
6218       = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6219                                                              : PK_Pointer)
6220         : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6221         : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6222 
6223     auto diag = state.getSema().Diag(attr.getLoc(),
6224                                      diag::warn_nullability_declspec)
6225       << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6226                              attr.isContextSensitiveKeywordAttribute())
6227       << type
6228       << static_cast<unsigned>(pointerKind);
6229 
6230     // FIXME: MemberPointer chunks don't carry the location of the *.
6231     if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6232       diag << FixItHint::CreateRemoval(attr.getLoc())
6233            << FixItHint::CreateInsertion(
6234                 state.getSema().getPreprocessor()
6235                   .getLocForEndOfToken(chunk.Loc),
6236                 " " + attr.getName()->getName().str() + " ");
6237     }
6238 
6239     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
6240                            chunk.getAttrListRef());
6241     return true;
6242   };
6243 
6244   // Move it to the outermost pointer, member pointer, or block
6245   // pointer declarator.
6246   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6247     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6248     switch (chunk.Kind) {
6249     case DeclaratorChunk::Pointer:
6250     case DeclaratorChunk::BlockPointer:
6251     case DeclaratorChunk::MemberPointer:
6252       return moveToChunk(chunk, false);
6253 
6254     case DeclaratorChunk::Paren:
6255     case DeclaratorChunk::Array:
6256       continue;
6257 
6258     case DeclaratorChunk::Function:
6259       // Try to move past the return type to a function/block/member
6260       // function pointer.
6261       if (DeclaratorChunk *dest = maybeMovePastReturnType(
6262                                     declarator, i,
6263                                     /*onlyBlockPointers=*/false)) {
6264         return moveToChunk(*dest, true);
6265       }
6266 
6267       return false;
6268 
6269     // Don't walk through these.
6270     case DeclaratorChunk::Reference:
6271     case DeclaratorChunk::Pipe:
6272       return false;
6273     }
6274   }
6275 
6276   return false;
6277 }
6278 
6279 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
6280   assert(!Attr.isInvalid());
6281   switch (Attr.getKind()) {
6282   default:
6283     llvm_unreachable("not a calling convention attribute");
6284   case AttributeList::AT_CDecl:
6285     return AttributedType::attr_cdecl;
6286   case AttributeList::AT_FastCall:
6287     return AttributedType::attr_fastcall;
6288   case AttributeList::AT_StdCall:
6289     return AttributedType::attr_stdcall;
6290   case AttributeList::AT_ThisCall:
6291     return AttributedType::attr_thiscall;
6292   case AttributeList::AT_RegCall:
6293     return AttributedType::attr_regcall;
6294   case AttributeList::AT_Pascal:
6295     return AttributedType::attr_pascal;
6296   case AttributeList::AT_SwiftCall:
6297     return AttributedType::attr_swiftcall;
6298   case AttributeList::AT_VectorCall:
6299     return AttributedType::attr_vectorcall;
6300   case AttributeList::AT_Pcs: {
6301     // The attribute may have had a fixit applied where we treated an
6302     // identifier as a string literal.  The contents of the string are valid,
6303     // but the form may not be.
6304     StringRef Str;
6305     if (Attr.isArgExpr(0))
6306       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6307     else
6308       Str = Attr.getArgAsIdent(0)->Ident->getName();
6309     return llvm::StringSwitch<AttributedType::Kind>(Str)
6310         .Case("aapcs", AttributedType::attr_pcs)
6311         .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6312   }
6313   case AttributeList::AT_IntelOclBicc:
6314     return AttributedType::attr_inteloclbicc;
6315   case AttributeList::AT_MSABI:
6316     return AttributedType::attr_ms_abi;
6317   case AttributeList::AT_SysVABI:
6318     return AttributedType::attr_sysv_abi;
6319   case AttributeList::AT_PreserveMost:
6320     return AttributedType::attr_preserve_most;
6321   case AttributeList::AT_PreserveAll:
6322     return AttributedType::attr_preserve_all;
6323   }
6324   llvm_unreachable("unexpected attribute kind!");
6325 }
6326 
6327 /// Process an individual function attribute.  Returns true to
6328 /// indicate that the attribute was handled, false if it wasn't.
6329 static bool handleFunctionTypeAttr(TypeProcessingState &state,
6330                                    AttributeList &attr,
6331                                    QualType &type) {
6332   Sema &S = state.getSema();
6333 
6334   FunctionTypeUnwrapper unwrapped(S, type);
6335 
6336   if (attr.getKind() == AttributeList::AT_NoReturn) {
6337     if (S.CheckNoReturnAttr(attr))
6338       return true;
6339 
6340     // Delay if this is not a function type.
6341     if (!unwrapped.isFunctionType())
6342       return false;
6343 
6344     // Otherwise we can process right away.
6345     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6346     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6347     return true;
6348   }
6349 
6350   // ns_returns_retained is not always a type attribute, but if we got
6351   // here, we're treating it as one right now.
6352   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
6353     assert(S.getLangOpts().ObjCAutoRefCount &&
6354            "ns_returns_retained treated as type attribute in non-ARC");
6355     if (attr.getNumArgs()) return true;
6356 
6357     // Delay if this is not a function type.
6358     if (!unwrapped.isFunctionType())
6359       return false;
6360 
6361     FunctionType::ExtInfo EI
6362       = unwrapped.get()->getExtInfo().withProducesResult(true);
6363     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6364     return true;
6365   }
6366 
6367   if (attr.getKind() == AttributeList::AT_Regparm) {
6368     unsigned value;
6369     if (S.CheckRegparmAttr(attr, value))
6370       return true;
6371 
6372     // Delay if this is not a function type.
6373     if (!unwrapped.isFunctionType())
6374       return false;
6375 
6376     // Diagnose regparm with fastcall.
6377     const FunctionType *fn = unwrapped.get();
6378     CallingConv CC = fn->getCallConv();
6379     if (CC == CC_X86FastCall) {
6380       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6381         << FunctionType::getNameForCallConv(CC)
6382         << "regparm";
6383       attr.setInvalid();
6384       return true;
6385     }
6386 
6387     FunctionType::ExtInfo EI =
6388       unwrapped.get()->getExtInfo().withRegParm(value);
6389     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6390     return true;
6391   }
6392 
6393   // Delay if the type didn't work out to a function.
6394   if (!unwrapped.isFunctionType()) return false;
6395 
6396   // Otherwise, a calling convention.
6397   CallingConv CC;
6398   if (S.CheckCallingConvAttr(attr, CC))
6399     return true;
6400 
6401   const FunctionType *fn = unwrapped.get();
6402   CallingConv CCOld = fn->getCallConv();
6403   AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6404 
6405   if (CCOld != CC) {
6406     // Error out on when there's already an attribute on the type
6407     // and the CCs don't match.
6408     const AttributedType *AT = S.getCallingConvAttributedType(type);
6409     if (AT && AT->getAttrKind() != CCAttrKind) {
6410       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6411         << FunctionType::getNameForCallConv(CC)
6412         << FunctionType::getNameForCallConv(CCOld);
6413       attr.setInvalid();
6414       return true;
6415     }
6416   }
6417 
6418   // Diagnose use of variadic functions with calling conventions that
6419   // don't support them (e.g. because they're callee-cleanup).
6420   // We delay warning about this on unprototyped function declarations
6421   // until after redeclaration checking, just in case we pick up a
6422   // prototype that way.  And apparently we also "delay" warning about
6423   // unprototyped function types in general, despite not necessarily having
6424   // much ability to diagnose it later.
6425   if (!supportsVariadicCall(CC)) {
6426     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6427     if (FnP && FnP->isVariadic()) {
6428       unsigned DiagID = diag::err_cconv_varargs;
6429 
6430       // stdcall and fastcall are ignored with a warning for GCC and MS
6431       // compatibility.
6432       bool IsInvalid = true;
6433       if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6434         DiagID = diag::warn_cconv_varargs;
6435         IsInvalid = false;
6436       }
6437 
6438       S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6439       if (IsInvalid) attr.setInvalid();
6440       return true;
6441     }
6442   }
6443 
6444   // Also diagnose fastcall with regparm.
6445   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6446     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6447         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6448     attr.setInvalid();
6449     return true;
6450   }
6451 
6452   // Modify the CC from the wrapped function type, wrap it all back, and then
6453   // wrap the whole thing in an AttributedType as written.  The modified type
6454   // might have a different CC if we ignored the attribute.
6455   QualType Equivalent;
6456   if (CCOld == CC) {
6457     Equivalent = type;
6458   } else {
6459     auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6460     Equivalent =
6461       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6462   }
6463   type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6464   return true;
6465 }
6466 
6467 bool Sema::hasExplicitCallingConv(QualType &T) {
6468   QualType R = T.IgnoreParens();
6469   while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6470     if (AT->isCallingConv())
6471       return true;
6472     R = AT->getModifiedType().IgnoreParens();
6473   }
6474   return false;
6475 }
6476 
6477 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6478                                   SourceLocation Loc) {
6479   FunctionTypeUnwrapper Unwrapped(*this, T);
6480   const FunctionType *FT = Unwrapped.get();
6481   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6482                      cast<FunctionProtoType>(FT)->isVariadic());
6483   CallingConv CurCC = FT->getCallConv();
6484   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6485 
6486   if (CurCC == ToCC)
6487     return;
6488 
6489   // MS compiler ignores explicit calling convention attributes on structors. We
6490   // should do the same.
6491   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6492     // Issue a warning on ignored calling convention -- except of __stdcall.
6493     // Again, this is what MS compiler does.
6494     if (CurCC != CC_X86StdCall)
6495       Diag(Loc, diag::warn_cconv_structors)
6496           << FunctionType::getNameForCallConv(CurCC);
6497   // Default adjustment.
6498   } else {
6499     // Only adjust types with the default convention.  For example, on Windows
6500     // we should adjust a __cdecl type to __thiscall for instance methods, and a
6501     // __thiscall type to __cdecl for static methods.
6502     CallingConv DefaultCC =
6503         Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6504 
6505     if (CurCC != DefaultCC || DefaultCC == ToCC)
6506       return;
6507 
6508     if (hasExplicitCallingConv(T))
6509       return;
6510   }
6511 
6512   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6513   QualType Wrapped = Unwrapped.wrap(*this, FT);
6514   T = Context.getAdjustedType(T, Wrapped);
6515 }
6516 
6517 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6518 /// and float scalars, although arrays, pointers, and function return values are
6519 /// allowed in conjunction with this construct. Aggregates with this attribute
6520 /// are invalid, even if they are of the same size as a corresponding scalar.
6521 /// The raw attribute should contain precisely 1 argument, the vector size for
6522 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6523 /// this routine will return a new vector type.
6524 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6525                                  Sema &S) {
6526   // Check the attribute arguments.
6527   if (Attr.getNumArgs() != 1) {
6528     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6529       << Attr.getName() << 1;
6530     Attr.setInvalid();
6531     return;
6532   }
6533   Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6534   llvm::APSInt vecSize(32);
6535   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6536       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6537     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6538       << Attr.getName() << AANT_ArgumentIntegerConstant
6539       << sizeExpr->getSourceRange();
6540     Attr.setInvalid();
6541     return;
6542   }
6543   // The base type must be integer (not Boolean or enumeration) or float, and
6544   // can't already be a vector.
6545   if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6546       (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6547     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6548     Attr.setInvalid();
6549     return;
6550   }
6551   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6552   // vecSize is specified in bytes - convert to bits.
6553   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6554 
6555   // the vector size needs to be an integral multiple of the type size.
6556   if (vectorSize % typeSize) {
6557     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6558       << sizeExpr->getSourceRange();
6559     Attr.setInvalid();
6560     return;
6561   }
6562   if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6563     S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6564       << sizeExpr->getSourceRange();
6565     Attr.setInvalid();
6566     return;
6567   }
6568   if (vectorSize == 0) {
6569     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6570       << sizeExpr->getSourceRange();
6571     Attr.setInvalid();
6572     return;
6573   }
6574 
6575   // Success! Instantiate the vector type, the number of elements is > 0, and
6576   // not required to be a power of 2, unlike GCC.
6577   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6578                                     VectorType::GenericVector);
6579 }
6580 
6581 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6582 /// a type.
6583 static void HandleExtVectorTypeAttr(QualType &CurType,
6584                                     const AttributeList &Attr,
6585                                     Sema &S) {
6586   // check the attribute arguments.
6587   if (Attr.getNumArgs() != 1) {
6588     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6589       << Attr.getName() << 1;
6590     return;
6591   }
6592 
6593   Expr *sizeExpr;
6594 
6595   // Special case where the argument is a template id.
6596   if (Attr.isArgIdent(0)) {
6597     CXXScopeSpec SS;
6598     SourceLocation TemplateKWLoc;
6599     UnqualifiedId id;
6600     id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6601 
6602     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6603                                           id, false, false);
6604     if (Size.isInvalid())
6605       return;
6606 
6607     sizeExpr = Size.get();
6608   } else {
6609     sizeExpr = Attr.getArgAsExpr(0);
6610   }
6611 
6612   // Create the vector type.
6613   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6614   if (!T.isNull())
6615     CurType = T;
6616 }
6617 
6618 static bool isPermittedNeonBaseType(QualType &Ty,
6619                                     VectorType::VectorKind VecKind, Sema &S) {
6620   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6621   if (!BTy)
6622     return false;
6623 
6624   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6625 
6626   // Signed poly is mathematically wrong, but has been baked into some ABIs by
6627   // now.
6628   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6629                         Triple.getArch() == llvm::Triple::aarch64_be;
6630   if (VecKind == VectorType::NeonPolyVector) {
6631     if (IsPolyUnsigned) {
6632       // AArch64 polynomial vectors are unsigned and support poly64.
6633       return BTy->getKind() == BuiltinType::UChar ||
6634              BTy->getKind() == BuiltinType::UShort ||
6635              BTy->getKind() == BuiltinType::ULong ||
6636              BTy->getKind() == BuiltinType::ULongLong;
6637     } else {
6638       // AArch32 polynomial vector are signed.
6639       return BTy->getKind() == BuiltinType::SChar ||
6640              BTy->getKind() == BuiltinType::Short;
6641     }
6642   }
6643 
6644   // Non-polynomial vector types: the usual suspects are allowed, as well as
6645   // float64_t on AArch64.
6646   bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6647                  Triple.getArch() == llvm::Triple::aarch64_be;
6648 
6649   if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6650     return true;
6651 
6652   return BTy->getKind() == BuiltinType::SChar ||
6653          BTy->getKind() == BuiltinType::UChar ||
6654          BTy->getKind() == BuiltinType::Short ||
6655          BTy->getKind() == BuiltinType::UShort ||
6656          BTy->getKind() == BuiltinType::Int ||
6657          BTy->getKind() == BuiltinType::UInt ||
6658          BTy->getKind() == BuiltinType::Long ||
6659          BTy->getKind() == BuiltinType::ULong ||
6660          BTy->getKind() == BuiltinType::LongLong ||
6661          BTy->getKind() == BuiltinType::ULongLong ||
6662          BTy->getKind() == BuiltinType::Float ||
6663          BTy->getKind() == BuiltinType::Half;
6664 }
6665 
6666 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6667 /// "neon_polyvector_type" attributes are used to create vector types that
6668 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
6669 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
6670 /// the argument to these Neon attributes is the number of vector elements,
6671 /// not the vector size in bytes.  The vector width and element type must
6672 /// match one of the standard Neon vector types.
6673 static void HandleNeonVectorTypeAttr(QualType& CurType,
6674                                      const AttributeList &Attr, Sema &S,
6675                                      VectorType::VectorKind VecKind) {
6676   // Target must have NEON
6677   if (!S.Context.getTargetInfo().hasFeature("neon")) {
6678     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6679     Attr.setInvalid();
6680     return;
6681   }
6682   // Check the attribute arguments.
6683   if (Attr.getNumArgs() != 1) {
6684     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6685       << Attr.getName() << 1;
6686     Attr.setInvalid();
6687     return;
6688   }
6689   // The number of elements must be an ICE.
6690   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6691   llvm::APSInt numEltsInt(32);
6692   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6693       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6694     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6695       << Attr.getName() << AANT_ArgumentIntegerConstant
6696       << numEltsExpr->getSourceRange();
6697     Attr.setInvalid();
6698     return;
6699   }
6700   // Only certain element types are supported for Neon vectors.
6701   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6702     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6703     Attr.setInvalid();
6704     return;
6705   }
6706 
6707   // The total size of the vector must be 64 or 128 bits.
6708   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6709   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6710   unsigned vecSize = typeSize * numElts;
6711   if (vecSize != 64 && vecSize != 128) {
6712     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6713     Attr.setInvalid();
6714     return;
6715   }
6716 
6717   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6718 }
6719 
6720 /// Handle OpenCL Access Qualifier Attribute.
6721 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr,
6722                                    Sema &S) {
6723   // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
6724   if (!(CurType->isImageType() || CurType->isPipeType())) {
6725     S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
6726     Attr.setInvalid();
6727     return;
6728   }
6729 
6730   if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
6731     QualType PointeeTy = TypedefTy->desugar();
6732     S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
6733 
6734     std::string PrevAccessQual;
6735     switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) {
6736       #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6737     case BuiltinType::Id:                                          \
6738       PrevAccessQual = #Access;                                    \
6739       break;
6740       #include "clang/Basic/OpenCLImageTypes.def"
6741     default:
6742       assert(0 && "Unable to find corresponding image type.");
6743     }
6744 
6745     S.Diag(TypedefTy->getDecl()->getLocStart(),
6746        diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
6747   } else if (CurType->isPipeType()) {
6748     if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
6749       QualType ElemType = CurType->getAs<PipeType>()->getElementType();
6750       CurType = S.Context.getWritePipeType(ElemType);
6751     }
6752   }
6753 }
6754 
6755 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6756                              TypeAttrLocation TAL, AttributeList *attrs) {
6757   // Scan through and apply attributes to this type where it makes sense.  Some
6758   // attributes (such as __address_space__, __vector_size__, etc) apply to the
6759   // type, but others can be present in the type specifiers even though they
6760   // apply to the decl.  Here we apply type attributes and ignore the rest.
6761 
6762   bool hasOpenCLAddressSpace = false;
6763   while (attrs) {
6764     AttributeList &attr = *attrs;
6765     attrs = attr.getNext(); // reset to the next here due to early loop continue
6766                             // stmts
6767 
6768     // Skip attributes that were marked to be invalid.
6769     if (attr.isInvalid())
6770       continue;
6771 
6772     if (attr.isCXX11Attribute()) {
6773       // [[gnu::...]] attributes are treated as declaration attributes, so may
6774       // not appertain to a DeclaratorChunk, even if we handle them as type
6775       // attributes.
6776       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6777         if (TAL == TAL_DeclChunk) {
6778           state.getSema().Diag(attr.getLoc(),
6779                                diag::warn_cxx11_gnu_attribute_on_type)
6780               << attr.getName();
6781           continue;
6782         }
6783       } else if (TAL != TAL_DeclChunk) {
6784         // Otherwise, only consider type processing for a C++11 attribute if
6785         // it's actually been applied to a type.
6786         continue;
6787       }
6788     }
6789 
6790     // If this is an attribute we can handle, do so now,
6791     // otherwise, add it to the FnAttrs list for rechaining.
6792     switch (attr.getKind()) {
6793     default:
6794       // A C++11 attribute on a declarator chunk must appertain to a type.
6795       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6796         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6797           << attr.getName();
6798         attr.setUsedAsTypeAttr();
6799       }
6800       break;
6801 
6802     case AttributeList::UnknownAttribute:
6803       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6804         state.getSema().Diag(attr.getLoc(),
6805                              diag::warn_unknown_attribute_ignored)
6806           << attr.getName();
6807       break;
6808 
6809     case AttributeList::IgnoredAttribute:
6810       break;
6811 
6812     case AttributeList::AT_MayAlias:
6813       // FIXME: This attribute needs to actually be handled, but if we ignore
6814       // it it breaks large amounts of Linux software.
6815       attr.setUsedAsTypeAttr();
6816       break;
6817     case AttributeList::AT_OpenCLPrivateAddressSpace:
6818     case AttributeList::AT_OpenCLGlobalAddressSpace:
6819     case AttributeList::AT_OpenCLLocalAddressSpace:
6820     case AttributeList::AT_OpenCLConstantAddressSpace:
6821     case AttributeList::AT_OpenCLGenericAddressSpace:
6822     case AttributeList::AT_AddressSpace:
6823       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6824       attr.setUsedAsTypeAttr();
6825       hasOpenCLAddressSpace = true;
6826       break;
6827     OBJC_POINTER_TYPE_ATTRS_CASELIST:
6828       if (!handleObjCPointerTypeAttr(state, attr, type))
6829         distributeObjCPointerTypeAttr(state, attr, type);
6830       attr.setUsedAsTypeAttr();
6831       break;
6832     case AttributeList::AT_VectorSize:
6833       HandleVectorSizeAttr(type, attr, state.getSema());
6834       attr.setUsedAsTypeAttr();
6835       break;
6836     case AttributeList::AT_ExtVectorType:
6837       HandleExtVectorTypeAttr(type, attr, state.getSema());
6838       attr.setUsedAsTypeAttr();
6839       break;
6840     case AttributeList::AT_NeonVectorType:
6841       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6842                                VectorType::NeonVector);
6843       attr.setUsedAsTypeAttr();
6844       break;
6845     case AttributeList::AT_NeonPolyVectorType:
6846       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6847                                VectorType::NeonPolyVector);
6848       attr.setUsedAsTypeAttr();
6849       break;
6850     case AttributeList::AT_OpenCLAccess:
6851       HandleOpenCLAccessAttr(type, attr, state.getSema());
6852       attr.setUsedAsTypeAttr();
6853       break;
6854 
6855     MS_TYPE_ATTRS_CASELIST:
6856       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6857         attr.setUsedAsTypeAttr();
6858       break;
6859 
6860 
6861     NULLABILITY_TYPE_ATTRS_CASELIST:
6862       // Either add nullability here or try to distribute it.  We
6863       // don't want to distribute the nullability specifier past any
6864       // dependent type, because that complicates the user model.
6865       if (type->canHaveNullability() || type->isDependentType() ||
6866           type->isArrayType() ||
6867           !distributeNullabilityTypeAttr(state, type, attr)) {
6868         unsigned endIndex;
6869         if (TAL == TAL_DeclChunk)
6870           endIndex = state.getCurrentChunkIndex();
6871         else
6872           endIndex = state.getDeclarator().getNumTypeObjects();
6873         bool allowOnArrayType =
6874             state.getDeclarator().isPrototypeContext() &&
6875             !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
6876         if (state.getSema().checkNullabilityTypeSpecifier(
6877               type,
6878               mapNullabilityAttrKind(attr.getKind()),
6879               attr.getLoc(),
6880               attr.isContextSensitiveKeywordAttribute(),
6881               allowOnArrayType)) {
6882           attr.setInvalid();
6883         }
6884 
6885         attr.setUsedAsTypeAttr();
6886       }
6887       break;
6888 
6889     case AttributeList::AT_ObjCKindOf:
6890       // '__kindof' must be part of the decl-specifiers.
6891       switch (TAL) {
6892       case TAL_DeclSpec:
6893         break;
6894 
6895       case TAL_DeclChunk:
6896       case TAL_DeclName:
6897         state.getSema().Diag(attr.getLoc(),
6898                              diag::err_objc_kindof_wrong_position)
6899           << FixItHint::CreateRemoval(attr.getLoc())
6900           << FixItHint::CreateInsertion(
6901                state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6902         break;
6903       }
6904 
6905       // Apply it regardless.
6906       if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6907         attr.setInvalid();
6908       attr.setUsedAsTypeAttr();
6909       break;
6910 
6911     case AttributeList::AT_NSReturnsRetained:
6912       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6913         break;
6914       // fallthrough into the function attrs
6915 
6916     FUNCTION_TYPE_ATTRS_CASELIST:
6917       attr.setUsedAsTypeAttr();
6918 
6919       // Never process function type attributes as part of the
6920       // declaration-specifiers.
6921       if (TAL == TAL_DeclSpec)
6922         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6923 
6924       // Otherwise, handle the possible delays.
6925       else if (!handleFunctionTypeAttr(state, attr, type))
6926         distributeFunctionTypeAttr(state, attr, type);
6927       break;
6928     }
6929   }
6930 
6931   // If address space is not set, OpenCL 2.0 defines non private default
6932   // address spaces for some cases:
6933   // OpenCL 2.0, section 6.5:
6934   // The address space for a variable at program scope or a static variable
6935   // inside a function can either be __global or __constant, but defaults to
6936   // __global if not specified.
6937   // (...)
6938   // Pointers that are declared without pointing to a named address space point
6939   // to the generic address space.
6940   if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
6941       !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
6942       (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
6943     Declarator &D = state.getDeclarator();
6944     if (state.getCurrentChunkIndex() > 0 &&
6945         (D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6946              DeclaratorChunk::Pointer ||
6947          D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6948              DeclaratorChunk::BlockPointer)) {
6949       type = state.getSema().Context.getAddrSpaceQualType(
6950           type, LangAS::opencl_generic);
6951     } else if (state.getCurrentChunkIndex() == 0 &&
6952                D.getContext() == Declarator::FileContext &&
6953                !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
6954                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6955                !type->isSamplerT())
6956       type = state.getSema().Context.getAddrSpaceQualType(
6957           type, LangAS::opencl_global);
6958     else if (state.getCurrentChunkIndex() == 0 &&
6959              D.getContext() == Declarator::BlockContext &&
6960              D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
6961       type = state.getSema().Context.getAddrSpaceQualType(
6962           type, LangAS::opencl_global);
6963   }
6964 }
6965 
6966 void Sema::completeExprArrayBound(Expr *E) {
6967   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6968     if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6969       if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6970         SourceLocation PointOfInstantiation = E->getExprLoc();
6971 
6972         if (MemberSpecializationInfo *MSInfo =
6973                 Var->getMemberSpecializationInfo()) {
6974           // If we don't already have a point of instantiation, this is it.
6975           if (MSInfo->getPointOfInstantiation().isInvalid()) {
6976             MSInfo->setPointOfInstantiation(PointOfInstantiation);
6977 
6978             // This is a modification of an existing AST node. Notify
6979             // listeners.
6980             if (ASTMutationListener *L = getASTMutationListener())
6981               L->StaticDataMemberInstantiated(Var);
6982           }
6983         } else {
6984           VarTemplateSpecializationDecl *VarSpec =
6985               cast<VarTemplateSpecializationDecl>(Var);
6986           if (VarSpec->getPointOfInstantiation().isInvalid())
6987             VarSpec->setPointOfInstantiation(PointOfInstantiation);
6988         }
6989 
6990         InstantiateVariableDefinition(PointOfInstantiation, Var);
6991 
6992         // Update the type to the newly instantiated definition's type both
6993         // here and within the expression.
6994         if (VarDecl *Def = Var->getDefinition()) {
6995           DRE->setDecl(Def);
6996           QualType T = Def->getType();
6997           DRE->setType(T);
6998           // FIXME: Update the type on all intervening expressions.
6999           E->setType(T);
7000         }
7001 
7002         // We still go on to try to complete the type independently, as it
7003         // may also require instantiations or diagnostics if it remains
7004         // incomplete.
7005       }
7006     }
7007   }
7008 }
7009 
7010 /// \brief Ensure that the type of the given expression is complete.
7011 ///
7012 /// This routine checks whether the expression \p E has a complete type. If the
7013 /// expression refers to an instantiable construct, that instantiation is
7014 /// performed as needed to complete its type. Furthermore
7015 /// Sema::RequireCompleteType is called for the expression's type (or in the
7016 /// case of a reference type, the referred-to type).
7017 ///
7018 /// \param E The expression whose type is required to be complete.
7019 /// \param Diagnoser The object that will emit a diagnostic if the type is
7020 /// incomplete.
7021 ///
7022 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
7023 /// otherwise.
7024 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
7025   QualType T = E->getType();
7026 
7027   // Incomplete array types may be completed by the initializer attached to
7028   // their definitions. For static data members of class templates and for
7029   // variable templates, we need to instantiate the definition to get this
7030   // initializer and complete the type.
7031   if (T->isIncompleteArrayType()) {
7032     completeExprArrayBound(E);
7033     T = E->getType();
7034   }
7035 
7036   // FIXME: Are there other cases which require instantiating something other
7037   // than the type to complete the type of an expression?
7038 
7039   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
7040 }
7041 
7042 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
7043   BoundTypeDiagnoser<> Diagnoser(DiagID);
7044   return RequireCompleteExprType(E, Diagnoser);
7045 }
7046 
7047 /// @brief Ensure that the type T is a complete type.
7048 ///
7049 /// This routine checks whether the type @p T is complete in any
7050 /// context where a complete type is required. If @p T is a complete
7051 /// type, returns false. If @p T is a class template specialization,
7052 /// this routine then attempts to perform class template
7053 /// instantiation. If instantiation fails, or if @p T is incomplete
7054 /// and cannot be completed, issues the diagnostic @p diag (giving it
7055 /// the type @p T) and returns true.
7056 ///
7057 /// @param Loc  The location in the source that the incomplete type
7058 /// diagnostic should refer to.
7059 ///
7060 /// @param T  The type that this routine is examining for completeness.
7061 ///
7062 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7063 /// @c false otherwise.
7064 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7065                                TypeDiagnoser &Diagnoser) {
7066   if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7067     return true;
7068   if (const TagType *Tag = T->getAs<TagType>()) {
7069     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7070       Tag->getDecl()->setCompleteDefinitionRequired();
7071       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7072     }
7073   }
7074   return false;
7075 }
7076 
7077 /// \brief Determine whether there is any declaration of \p D that was ever a
7078 ///        definition (perhaps before module merging) and is currently visible.
7079 /// \param D The definition of the entity.
7080 /// \param Suggested Filled in with the declaration that should be made visible
7081 ///        in order to provide a definition of this entity.
7082 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7083 ///        not defined. This only matters for enums with a fixed underlying
7084 ///        type, since in all other cases, a type is complete if and only if it
7085 ///        is defined.
7086 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
7087                                 bool OnlyNeedComplete) {
7088   // Easy case: if we don't have modules, all declarations are visible.
7089   if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7090     return true;
7091 
7092   // If this definition was instantiated from a template, map back to the
7093   // pattern from which it was instantiated.
7094   if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7095     // We're in the middle of defining it; this definition should be treated
7096     // as visible.
7097     return true;
7098   } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7099     if (auto *Pattern = RD->getTemplateInstantiationPattern())
7100       RD = Pattern;
7101     D = RD->getDefinition();
7102   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7103     if (auto *Pattern = ED->getTemplateInstantiationPattern())
7104       ED = Pattern;
7105     if (OnlyNeedComplete && ED->isFixed()) {
7106       // If the enum has a fixed underlying type, and we're only looking for a
7107       // complete type (not a definition), any visible declaration of it will
7108       // do.
7109       *Suggested = nullptr;
7110       for (auto *Redecl : ED->redecls()) {
7111         if (isVisible(Redecl))
7112           return true;
7113         if (Redecl->isThisDeclarationADefinition() ||
7114             (Redecl->isCanonicalDecl() && !*Suggested))
7115           *Suggested = Redecl;
7116       }
7117       return false;
7118     }
7119     D = ED->getDefinition();
7120   } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7121     if (auto *Pattern = FD->getTemplateInstantiationPattern())
7122       FD = Pattern;
7123     D = FD->getDefinition();
7124   } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7125     if (auto *Pattern = VD->getTemplateInstantiationPattern())
7126       VD = Pattern;
7127     D = VD->getDefinition();
7128   }
7129   assert(D && "missing definition for pattern of instantiated definition");
7130 
7131   *Suggested = D;
7132   if (isVisible(D))
7133     return true;
7134 
7135   // The external source may have additional definitions of this entity that are
7136   // visible, so complete the redeclaration chain now and ask again.
7137   if (auto *Source = Context.getExternalSource()) {
7138     Source->CompleteRedeclChain(D);
7139     return isVisible(D);
7140   }
7141 
7142   return false;
7143 }
7144 
7145 /// Locks in the inheritance model for the given class and all of its bases.
7146 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
7147   RD = RD->getMostRecentDecl();
7148   if (!RD->hasAttr<MSInheritanceAttr>()) {
7149     MSInheritanceAttr::Spelling IM;
7150 
7151     switch (S.MSPointerToMemberRepresentationMethod) {
7152     case LangOptions::PPTMK_BestCase:
7153       IM = RD->calculateInheritanceModel();
7154       break;
7155     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
7156       IM = MSInheritanceAttr::Keyword_single_inheritance;
7157       break;
7158     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
7159       IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7160       break;
7161     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
7162       IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7163       break;
7164     }
7165 
7166     RD->addAttr(MSInheritanceAttr::CreateImplicit(
7167         S.getASTContext(), IM,
7168         /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7169             LangOptions::PPTMK_BestCase,
7170         S.ImplicitMSInheritanceAttrLoc.isValid()
7171             ? S.ImplicitMSInheritanceAttrLoc
7172             : RD->getSourceRange()));
7173     S.Consumer.AssignInheritanceModel(RD);
7174   }
7175 }
7176 
7177 /// \brief The implementation of RequireCompleteType
7178 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7179                                    TypeDiagnoser *Diagnoser) {
7180   // FIXME: Add this assertion to make sure we always get instantiation points.
7181   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7182   // FIXME: Add this assertion to help us flush out problems with
7183   // checking for dependent types and type-dependent expressions.
7184   //
7185   //  assert(!T->isDependentType() &&
7186   //         "Can't ask whether a dependent type is complete");
7187 
7188   // We lock in the inheritance model once somebody has asked us to ensure
7189   // that a pointer-to-member type is complete.
7190   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7191     if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7192       if (!MPTy->getClass()->isDependentType()) {
7193         (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7194         assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7195       }
7196     }
7197   }
7198 
7199   NamedDecl *Def = nullptr;
7200   bool Incomplete = T->isIncompleteType(&Def);
7201 
7202   // Check that any necessary explicit specializations are visible. For an
7203   // enum, we just need the declaration, so don't check this.
7204   if (Def && !isa<EnumDecl>(Def))
7205     checkSpecializationVisibility(Loc, Def);
7206 
7207   // If we have a complete type, we're done.
7208   if (!Incomplete) {
7209     // If we know about the definition but it is not visible, complain.
7210     NamedDecl *SuggestedDef = nullptr;
7211     if (Def &&
7212         !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7213       // If the user is going to see an error here, recover by making the
7214       // definition visible.
7215       bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7216       if (Diagnoser)
7217         diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7218                               /*Recover*/TreatAsComplete);
7219       return !TreatAsComplete;
7220     }
7221 
7222     return false;
7223   }
7224 
7225   const TagType *Tag = T->getAs<TagType>();
7226   const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
7227 
7228   // If there's an unimported definition of this type in a module (for
7229   // instance, because we forward declared it, then imported the definition),
7230   // import that definition now.
7231   //
7232   // FIXME: What about other cases where an import extends a redeclaration
7233   // chain for a declaration that can be accessed through a mechanism other
7234   // than name lookup (eg, referenced in a template, or a variable whose type
7235   // could be completed by the module)?
7236   //
7237   // FIXME: Should we map through to the base array element type before
7238   // checking for a tag type?
7239   if (Tag || IFace) {
7240     NamedDecl *D =
7241         Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
7242 
7243     // Avoid diagnosing invalid decls as incomplete.
7244     if (D->isInvalidDecl())
7245       return true;
7246 
7247     // Give the external AST source a chance to complete the type.
7248     if (auto *Source = Context.getExternalSource()) {
7249       if (Tag)
7250         Source->CompleteType(Tag->getDecl());
7251       else
7252         Source->CompleteType(IFace->getDecl());
7253 
7254       // If the external source completed the type, go through the motions
7255       // again to ensure we're allowed to use the completed type.
7256       if (!T->isIncompleteType())
7257         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7258     }
7259   }
7260 
7261   // If we have a class template specialization or a class member of a
7262   // class template specialization, or an array with known size of such,
7263   // try to instantiate it.
7264   QualType MaybeTemplate = T;
7265   while (const ConstantArrayType *Array
7266            = Context.getAsConstantArrayType(MaybeTemplate))
7267     MaybeTemplate = Array->getElementType();
7268   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
7269     bool Instantiated = false;
7270     bool Diagnosed = false;
7271     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
7272           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
7273       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7274         Diagnosed = InstantiateClassTemplateSpecialization(
7275             Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7276             /*Complain=*/Diagnoser);
7277         Instantiated = true;
7278       }
7279     } else if (CXXRecordDecl *Rec
7280                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
7281       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
7282       if (!Rec->isBeingDefined() && Pattern) {
7283         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
7284         assert(MSI && "Missing member specialization information?");
7285         // This record was instantiated from a class within a template.
7286         if (MSI->getTemplateSpecializationKind() !=
7287             TSK_ExplicitSpecialization) {
7288           Diagnosed = InstantiateClass(Loc, Rec, Pattern,
7289                                        getTemplateInstantiationArgs(Rec),
7290                                        TSK_ImplicitInstantiation,
7291                                        /*Complain=*/Diagnoser);
7292           Instantiated = true;
7293         }
7294       }
7295     }
7296 
7297     if (Instantiated) {
7298       // Instantiate* might have already complained that the template is not
7299       // defined, if we asked it to.
7300       if (Diagnoser && Diagnosed)
7301         return true;
7302       // If we instantiated a definition, check that it's usable, even if
7303       // instantiation produced an error, so that repeated calls to this
7304       // function give consistent answers.
7305       if (!T->isIncompleteType())
7306         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7307     }
7308   }
7309 
7310   // FIXME: If we didn't instantiate a definition because of an explicit
7311   // specialization declaration, check that it's visible.
7312 
7313   if (!Diagnoser)
7314     return true;
7315 
7316   Diagnoser->diagnose(*this, Loc, T);
7317 
7318   // If the type was a forward declaration of a class/struct/union
7319   // type, produce a note.
7320   if (Tag && !Tag->getDecl()->isInvalidDecl())
7321     Diag(Tag->getDecl()->getLocation(),
7322          Tag->isBeingDefined() ? diag::note_type_being_defined
7323                                : diag::note_forward_declaration)
7324       << QualType(Tag, 0);
7325 
7326   // If the Objective-C class was a forward declaration, produce a note.
7327   if (IFace && !IFace->getDecl()->isInvalidDecl())
7328     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7329 
7330   // If we have external information that we can use to suggest a fix,
7331   // produce a note.
7332   if (ExternalSource)
7333     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7334 
7335   return true;
7336 }
7337 
7338 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7339                                unsigned DiagID) {
7340   BoundTypeDiagnoser<> Diagnoser(DiagID);
7341   return RequireCompleteType(Loc, T, Diagnoser);
7342 }
7343 
7344 /// \brief Get diagnostic %select index for tag kind for
7345 /// literal type diagnostic message.
7346 /// WARNING: Indexes apply to particular diagnostics only!
7347 ///
7348 /// \returns diagnostic %select index.
7349 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7350   switch (Tag) {
7351   case TTK_Struct: return 0;
7352   case TTK_Interface: return 1;
7353   case TTK_Class:  return 2;
7354   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7355   }
7356 }
7357 
7358 /// @brief Ensure that the type T is a literal type.
7359 ///
7360 /// This routine checks whether the type @p T is a literal type. If @p T is an
7361 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7362 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7363 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7364 /// it the type @p T), along with notes explaining why the type is not a
7365 /// literal type, and returns true.
7366 ///
7367 /// @param Loc  The location in the source that the non-literal type
7368 /// diagnostic should refer to.
7369 ///
7370 /// @param T  The type that this routine is examining for literalness.
7371 ///
7372 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7373 ///
7374 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7375 /// @c false otherwise.
7376 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7377                               TypeDiagnoser &Diagnoser) {
7378   assert(!T->isDependentType() && "type should not be dependent");
7379 
7380   QualType ElemType = Context.getBaseElementType(T);
7381   if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7382       T->isLiteralType(Context))
7383     return false;
7384 
7385   Diagnoser.diagnose(*this, Loc, T);
7386 
7387   if (T->isVariableArrayType())
7388     return true;
7389 
7390   const RecordType *RT = ElemType->getAs<RecordType>();
7391   if (!RT)
7392     return true;
7393 
7394   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7395 
7396   // A partially-defined class type can't be a literal type, because a literal
7397   // class type must have a trivial destructor (which can't be checked until
7398   // the class definition is complete).
7399   if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7400     return true;
7401 
7402   // If the class has virtual base classes, then it's not an aggregate, and
7403   // cannot have any constexpr constructors or a trivial default constructor,
7404   // so is non-literal. This is better to diagnose than the resulting absence
7405   // of constexpr constructors.
7406   if (RD->getNumVBases()) {
7407     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7408       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7409     for (const auto &I : RD->vbases())
7410       Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7411           << I.getSourceRange();
7412   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7413              !RD->hasTrivialDefaultConstructor()) {
7414     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7415   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7416     for (const auto &I : RD->bases()) {
7417       if (!I.getType()->isLiteralType(Context)) {
7418         Diag(I.getLocStart(),
7419              diag::note_non_literal_base_class)
7420           << RD << I.getType() << I.getSourceRange();
7421         return true;
7422       }
7423     }
7424     for (const auto *I : RD->fields()) {
7425       if (!I->getType()->isLiteralType(Context) ||
7426           I->getType().isVolatileQualified()) {
7427         Diag(I->getLocation(), diag::note_non_literal_field)
7428           << RD << I << I->getType()
7429           << I->getType().isVolatileQualified();
7430         return true;
7431       }
7432     }
7433   } else if (!RD->hasTrivialDestructor()) {
7434     // All fields and bases are of literal types, so have trivial destructors.
7435     // If this class's destructor is non-trivial it must be user-declared.
7436     CXXDestructorDecl *Dtor = RD->getDestructor();
7437     assert(Dtor && "class has literal fields and bases but no dtor?");
7438     if (!Dtor)
7439       return true;
7440 
7441     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7442          diag::note_non_literal_user_provided_dtor :
7443          diag::note_non_literal_nontrivial_dtor) << RD;
7444     if (!Dtor->isUserProvided())
7445       SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
7446   }
7447 
7448   return true;
7449 }
7450 
7451 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7452   BoundTypeDiagnoser<> Diagnoser(DiagID);
7453   return RequireLiteralType(Loc, T, Diagnoser);
7454 }
7455 
7456 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
7457 /// and qualified by the nested-name-specifier contained in SS.
7458 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7459                                  const CXXScopeSpec &SS, QualType T) {
7460   if (T.isNull())
7461     return T;
7462   NestedNameSpecifier *NNS;
7463   if (SS.isValid())
7464     NNS = SS.getScopeRep();
7465   else {
7466     if (Keyword == ETK_None)
7467       return T;
7468     NNS = nullptr;
7469   }
7470   return Context.getElaboratedType(Keyword, NNS, T);
7471 }
7472 
7473 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7474   ExprResult ER = CheckPlaceholderExpr(E);
7475   if (ER.isInvalid()) return QualType();
7476   E = ER.get();
7477 
7478   if (!getLangOpts().CPlusPlus && E->refersToBitField())
7479     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7480 
7481   if (!E->isTypeDependent()) {
7482     QualType T = E->getType();
7483     if (const TagType *TT = T->getAs<TagType>())
7484       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7485   }
7486   return Context.getTypeOfExprType(E);
7487 }
7488 
7489 /// getDecltypeForExpr - Given an expr, will return the decltype for
7490 /// that expression, according to the rules in C++11
7491 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
7492 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7493   if (E->isTypeDependent())
7494     return S.Context.DependentTy;
7495 
7496   // C++11 [dcl.type.simple]p4:
7497   //   The type denoted by decltype(e) is defined as follows:
7498   //
7499   //     - if e is an unparenthesized id-expression or an unparenthesized class
7500   //       member access (5.2.5), decltype(e) is the type of the entity named
7501   //       by e. If there is no such entity, or if e names a set of overloaded
7502   //       functions, the program is ill-formed;
7503   //
7504   // We apply the same rules for Objective-C ivar and property references.
7505   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7506     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
7507       return VD->getType();
7508   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7509     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
7510       return FD->getType();
7511   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
7512     return IR->getDecl()->getType();
7513   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
7514     if (PR->isExplicitProperty())
7515       return PR->getExplicitProperty()->getType();
7516   } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
7517     return PE->getType();
7518   }
7519 
7520   // C++11 [expr.lambda.prim]p18:
7521   //   Every occurrence of decltype((x)) where x is a possibly
7522   //   parenthesized id-expression that names an entity of automatic
7523   //   storage duration is treated as if x were transformed into an
7524   //   access to a corresponding data member of the closure type that
7525   //   would have been declared if x were an odr-use of the denoted
7526   //   entity.
7527   using namespace sema;
7528   if (S.getCurLambda()) {
7529     if (isa<ParenExpr>(E)) {
7530       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7531         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7532           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
7533           if (!T.isNull())
7534             return S.Context.getLValueReferenceType(T);
7535         }
7536       }
7537     }
7538   }
7539 
7540 
7541   // C++11 [dcl.type.simple]p4:
7542   //   [...]
7543   QualType T = E->getType();
7544   switch (E->getValueKind()) {
7545   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
7546   //       type of e;
7547   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
7548   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
7549   //       type of e;
7550   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
7551   //  - otherwise, decltype(e) is the type of e.
7552   case VK_RValue: break;
7553   }
7554 
7555   return T;
7556 }
7557 
7558 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
7559                                  bool AsUnevaluated) {
7560   ExprResult ER = CheckPlaceholderExpr(E);
7561   if (ER.isInvalid()) return QualType();
7562   E = ER.get();
7563 
7564   if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
7565       E->HasSideEffects(Context, false)) {
7566     // The expression operand for decltype is in an unevaluated expression
7567     // context, so side effects could result in unintended consequences.
7568     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7569   }
7570 
7571   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7572 }
7573 
7574 QualType Sema::BuildUnaryTransformType(QualType BaseType,
7575                                        UnaryTransformType::UTTKind UKind,
7576                                        SourceLocation Loc) {
7577   switch (UKind) {
7578   case UnaryTransformType::EnumUnderlyingType:
7579     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7580       Diag(Loc, diag::err_only_enums_have_underlying_types);
7581       return QualType();
7582     } else {
7583       QualType Underlying = BaseType;
7584       if (!BaseType->isDependentType()) {
7585         // The enum could be incomplete if we're parsing its definition or
7586         // recovering from an error.
7587         NamedDecl *FwdDecl = nullptr;
7588         if (BaseType->isIncompleteType(&FwdDecl)) {
7589           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
7590           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
7591           return QualType();
7592         }
7593 
7594         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7595         assert(ED && "EnumType has no EnumDecl");
7596 
7597         DiagnoseUseOfDecl(ED, Loc);
7598 
7599         Underlying = ED->getIntegerType();
7600         assert(!Underlying.isNull());
7601       }
7602       return Context.getUnaryTransformType(BaseType, Underlying,
7603                                         UnaryTransformType::EnumUnderlyingType);
7604     }
7605   }
7606   llvm_unreachable("unknown unary transform type");
7607 }
7608 
7609 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
7610   if (!T->isDependentType()) {
7611     // FIXME: It isn't entirely clear whether incomplete atomic types
7612     // are allowed or not; for simplicity, ban them for the moment.
7613     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
7614       return QualType();
7615 
7616     int DisallowedKind = -1;
7617     if (T->isArrayType())
7618       DisallowedKind = 1;
7619     else if (T->isFunctionType())
7620       DisallowedKind = 2;
7621     else if (T->isReferenceType())
7622       DisallowedKind = 3;
7623     else if (T->isAtomicType())
7624       DisallowedKind = 4;
7625     else if (T.hasQualifiers())
7626       DisallowedKind = 5;
7627     else if (!T.isTriviallyCopyableType(Context))
7628       // Some other non-trivially-copyable type (probably a C++ class)
7629       DisallowedKind = 6;
7630 
7631     if (DisallowedKind != -1) {
7632       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7633       return QualType();
7634     }
7635 
7636     // FIXME: Do we need any handling for ARC here?
7637   }
7638 
7639   // Build the pointer type.
7640   return Context.getAtomicType(T);
7641 }
7642