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