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