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