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