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