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