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