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