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