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