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