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