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