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