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