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