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