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