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