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