SemaType.cpp revision 561d3abc881033776ece385a01a510e1cbc1fa92
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 ExplicitNone 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_ExplicitNone;
1065
1066  // If that failed, give an error and recover using __autoreleasing.
1067  } else {
1068    // These types can show up in private ivars in system headers, so
1069    // we need this to not be an error in those cases.  Instead we
1070    // want to delay.
1071    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1072      S.DelayedDiagnostics.add(
1073          sema::DelayedDiagnostic::makeForbiddenType(loc,
1074              diag::err_arc_indirect_no_ownership, type, isReference));
1075    } else {
1076      S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1077    }
1078    implicitLifetime = Qualifiers::OCL_Autoreleasing;
1079  }
1080  assert(implicitLifetime && "didn't infer any lifetime!");
1081
1082  Qualifiers qs;
1083  qs.addObjCLifetime(implicitLifetime);
1084  return S.Context.getQualifiedType(type, qs);
1085}
1086
1087/// \brief Build a pointer type.
1088///
1089/// \param T The type to which we'll be building a pointer.
1090///
1091/// \param Loc The location of the entity whose type involves this
1092/// pointer type or, if there is no such entity, the location of the
1093/// type that will have pointer type.
1094///
1095/// \param Entity The name of the entity that involves the pointer
1096/// type, if known.
1097///
1098/// \returns A suitable pointer type, if there are no
1099/// errors. Otherwise, returns a NULL type.
1100QualType Sema::BuildPointerType(QualType T,
1101                                SourceLocation Loc, DeclarationName Entity) {
1102  if (T->isReferenceType()) {
1103    // C++ 8.3.2p4: There shall be no ... pointers to references ...
1104    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1105      << getPrintableNameForEntity(Entity) << T;
1106    return QualType();
1107  }
1108
1109  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1110
1111  // In ARC, it is forbidden to build pointers to unqualified pointers.
1112  if (getLangOptions().ObjCAutoRefCount)
1113    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1114
1115  // Build the pointer type.
1116  return Context.getPointerType(T);
1117}
1118
1119/// \brief Build a reference type.
1120///
1121/// \param T The type to which we'll be building a reference.
1122///
1123/// \param Loc The location of the entity whose type involves this
1124/// reference type or, if there is no such entity, the location of the
1125/// type that will have reference type.
1126///
1127/// \param Entity The name of the entity that involves the reference
1128/// type, if known.
1129///
1130/// \returns A suitable reference type, if there are no
1131/// errors. Otherwise, returns a NULL type.
1132QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1133                                  SourceLocation Loc,
1134                                  DeclarationName Entity) {
1135  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1136         "Unresolved overloaded function type");
1137
1138  // C++0x [dcl.ref]p6:
1139  //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1140  //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1141  //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1142  //   the type "lvalue reference to T", while an attempt to create the type
1143  //   "rvalue reference to cv TR" creates the type TR.
1144  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1145
1146  // C++ [dcl.ref]p4: There shall be no references to references.
1147  //
1148  // According to C++ DR 106, references to references are only
1149  // diagnosed when they are written directly (e.g., "int & &"),
1150  // but not when they happen via a typedef:
1151  //
1152  //   typedef int& intref;
1153  //   typedef intref& intref2;
1154  //
1155  // Parser::ParseDeclaratorInternal diagnoses the case where
1156  // references are written directly; here, we handle the
1157  // collapsing of references-to-references as described in C++0x.
1158  // DR 106 and 540 introduce reference-collapsing into C++98/03.
1159
1160  // C++ [dcl.ref]p1:
1161  //   A declarator that specifies the type "reference to cv void"
1162  //   is ill-formed.
1163  if (T->isVoidType()) {
1164    Diag(Loc, diag::err_reference_to_void);
1165    return QualType();
1166  }
1167
1168  // In ARC, it is forbidden to build references to unqualified pointers.
1169  if (getLangOptions().ObjCAutoRefCount)
1170    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1171
1172  // Handle restrict on references.
1173  if (LValueRef)
1174    return Context.getLValueReferenceType(T, SpelledAsLValue);
1175  return Context.getRValueReferenceType(T);
1176}
1177
1178/// Check whether the specified array size makes the array type a VLA.  If so,
1179/// return true, if not, return the size of the array in SizeVal.
1180static bool isArraySizeVLA(Expr *ArraySize, llvm::APSInt &SizeVal, Sema &S) {
1181  // If the size is an ICE, it certainly isn't a VLA.
1182  if (ArraySize->isIntegerConstantExpr(SizeVal, S.Context))
1183    return false;
1184
1185  // If we're in a GNU mode (like gnu99, but not c99) accept any evaluatable
1186  // value as an extension.
1187  if (S.LangOpts.GNUMode && ArraySize->EvaluateAsInt(SizeVal, S.Context)) {
1188    S.Diag(ArraySize->getLocStart(), diag::ext_vla_folded_to_constant);
1189    return false;
1190  }
1191
1192  return true;
1193}
1194
1195
1196/// \brief Build an array type.
1197///
1198/// \param T The type of each element in the array.
1199///
1200/// \param ASM C99 array size modifier (e.g., '*', 'static').
1201///
1202/// \param ArraySize Expression describing the size of the array.
1203///
1204/// \param Loc The location of the entity whose type involves this
1205/// array type or, if there is no such entity, the location of the
1206/// type that will have array type.
1207///
1208/// \param Entity The name of the entity that involves the array
1209/// type, if known.
1210///
1211/// \returns A suitable array type, if there are no errors. Otherwise,
1212/// returns a NULL type.
1213QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1214                              Expr *ArraySize, unsigned Quals,
1215                              SourceRange Brackets, DeclarationName Entity) {
1216
1217  SourceLocation Loc = Brackets.getBegin();
1218  if (getLangOptions().CPlusPlus) {
1219    // C++ [dcl.array]p1:
1220    //   T is called the array element type; this type shall not be a reference
1221    //   type, the (possibly cv-qualified) type void, a function type or an
1222    //   abstract class type.
1223    //
1224    // Note: function types are handled in the common path with C.
1225    if (T->isReferenceType()) {
1226      Diag(Loc, diag::err_illegal_decl_array_of_references)
1227      << getPrintableNameForEntity(Entity) << T;
1228      return QualType();
1229    }
1230
1231    if (T->isVoidType()) {
1232      Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1233      return QualType();
1234    }
1235
1236    if (RequireNonAbstractType(Brackets.getBegin(), T,
1237                               diag::err_array_of_abstract_type))
1238      return QualType();
1239
1240  } else {
1241    // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1242    // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1243    if (RequireCompleteType(Loc, T,
1244                            diag::err_illegal_decl_array_incomplete_type))
1245      return QualType();
1246  }
1247
1248  if (T->isFunctionType()) {
1249    Diag(Loc, diag::err_illegal_decl_array_of_functions)
1250      << getPrintableNameForEntity(Entity) << T;
1251    return QualType();
1252  }
1253
1254  if (T->getContainedAutoType()) {
1255    Diag(Loc, diag::err_illegal_decl_array_of_auto)
1256      << getPrintableNameForEntity(Entity) << T;
1257    return QualType();
1258  }
1259
1260  if (const RecordType *EltTy = T->getAs<RecordType>()) {
1261    // If the element type is a struct or union that contains a variadic
1262    // array, accept it as a GNU extension: C99 6.7.2.1p2.
1263    if (EltTy->getDecl()->hasFlexibleArrayMember())
1264      Diag(Loc, diag::ext_flexible_array_in_array) << T;
1265  } else if (T->isObjCObjectType()) {
1266    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1267    return QualType();
1268  }
1269
1270  // Do placeholder conversions on the array size expression.
1271  if (ArraySize && ArraySize->hasPlaceholderType()) {
1272    ExprResult Result = CheckPlaceholderExpr(ArraySize);
1273    if (Result.isInvalid()) return QualType();
1274    ArraySize = Result.take();
1275  }
1276
1277  // Do lvalue-to-rvalue conversions on the array size expression.
1278  if (ArraySize && !ArraySize->isRValue()) {
1279    ExprResult Result = DefaultLvalueConversion(ArraySize);
1280    if (Result.isInvalid())
1281      return QualType();
1282
1283    ArraySize = Result.take();
1284  }
1285
1286  // C99 6.7.5.2p1: The size expression shall have integer type.
1287  // TODO: in theory, if we were insane, we could allow contextual
1288  // conversions to integer type here.
1289  if (ArraySize && !ArraySize->isTypeDependent() &&
1290      !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1291    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1292      << ArraySize->getType() << ArraySize->getSourceRange();
1293    return QualType();
1294  }
1295  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1296  if (!ArraySize) {
1297    if (ASM == ArrayType::Star)
1298      T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1299    else
1300      T = Context.getIncompleteArrayType(T, ASM, Quals);
1301  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1302    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1303  } else if (!T->isDependentType() && !T->isIncompleteType() &&
1304             !T->isConstantSizeType()) {
1305    // C99: an array with an element type that has a non-constant-size is a VLA.
1306    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1307  } else if (isArraySizeVLA(ArraySize, ConstVal, *this)) {
1308    // C99: an array with a non-ICE size is a VLA.  We accept any expression
1309    // that we can fold to a non-zero positive value as an extension.
1310    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1311  } else {
1312    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1313    // have a value greater than zero.
1314    if (ConstVal.isSigned() && ConstVal.isNegative()) {
1315      if (Entity)
1316        Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1317          << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1318      else
1319        Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1320          << ArraySize->getSourceRange();
1321      return QualType();
1322    }
1323    if (ConstVal == 0) {
1324      // GCC accepts zero sized static arrays. We allow them when
1325      // we're not in a SFINAE context.
1326      Diag(ArraySize->getLocStart(),
1327           isSFINAEContext()? diag::err_typecheck_zero_array_size
1328                            : diag::ext_typecheck_zero_array_size)
1329        << ArraySize->getSourceRange();
1330
1331      if (ASM == ArrayType::Static) {
1332        Diag(ArraySize->getLocStart(),
1333             diag::warn_typecheck_zero_static_array_size)
1334          << ArraySize->getSourceRange();
1335        ASM = ArrayType::Normal;
1336      }
1337    } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1338               !T->isIncompleteType()) {
1339      // Is the array too large?
1340      unsigned ActiveSizeBits
1341        = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1342      if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1343        Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1344          << ConstVal.toString(10)
1345          << ArraySize->getSourceRange();
1346    }
1347
1348    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1349  }
1350  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1351  if (!getLangOptions().C99) {
1352    if (T->isVariableArrayType()) {
1353      // Prohibit the use of non-POD types in VLAs.
1354      QualType BaseT = Context.getBaseElementType(T);
1355      if (!T->isDependentType() &&
1356          !BaseT.isPODType(Context) &&
1357          !BaseT->isObjCLifetimeType()) {
1358        Diag(Loc, diag::err_vla_non_pod)
1359          << BaseT;
1360        return QualType();
1361      }
1362      // Prohibit the use of VLAs during template argument deduction.
1363      else if (isSFINAEContext()) {
1364        Diag(Loc, diag::err_vla_in_sfinae);
1365        return QualType();
1366      }
1367      // Just extwarn about VLAs.
1368      else
1369        Diag(Loc, diag::ext_vla);
1370    } else if (ASM != ArrayType::Normal || Quals != 0)
1371      Diag(Loc,
1372           getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1373                                     : diag::ext_c99_array_usage) << ASM;
1374  }
1375
1376  return T;
1377}
1378
1379/// \brief Build an ext-vector type.
1380///
1381/// Run the required checks for the extended vector type.
1382QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1383                                  SourceLocation AttrLoc) {
1384  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1385  // in conjunction with complex types (pointers, arrays, functions, etc.).
1386  if (!T->isDependentType() &&
1387      !T->isIntegerType() && !T->isRealFloatingType()) {
1388    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1389    return QualType();
1390  }
1391
1392  if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1393    llvm::APSInt vecSize(32);
1394    if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1395      Diag(AttrLoc, diag::err_attribute_argument_not_int)
1396        << "ext_vector_type" << ArraySize->getSourceRange();
1397      return QualType();
1398    }
1399
1400    // unlike gcc's vector_size attribute, the size is specified as the
1401    // number of elements, not the number of bytes.
1402    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1403
1404    if (vectorSize == 0) {
1405      Diag(AttrLoc, diag::err_attribute_zero_size)
1406      << ArraySize->getSourceRange();
1407      return QualType();
1408    }
1409
1410    return Context.getExtVectorType(T, vectorSize);
1411  }
1412
1413  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1414}
1415
1416/// \brief Build a function type.
1417///
1418/// This routine checks the function type according to C++ rules and
1419/// under the assumption that the result type and parameter types have
1420/// just been instantiated from a template. It therefore duplicates
1421/// some of the behavior of GetTypeForDeclarator, but in a much
1422/// simpler form that is only suitable for this narrow use case.
1423///
1424/// \param T The return type of the function.
1425///
1426/// \param ParamTypes The parameter types of the function. This array
1427/// will be modified to account for adjustments to the types of the
1428/// function parameters.
1429///
1430/// \param NumParamTypes The number of parameter types in ParamTypes.
1431///
1432/// \param Variadic Whether this is a variadic function type.
1433///
1434/// \param Quals The cvr-qualifiers to be applied to the function type.
1435///
1436/// \param Loc The location of the entity whose type involves this
1437/// function type or, if there is no such entity, the location of the
1438/// type that will have function type.
1439///
1440/// \param Entity The name of the entity that involves the function
1441/// type, if known.
1442///
1443/// \returns A suitable function type, if there are no
1444/// errors. Otherwise, returns a NULL type.
1445QualType Sema::BuildFunctionType(QualType T,
1446                                 QualType *ParamTypes,
1447                                 unsigned NumParamTypes,
1448                                 bool Variadic, unsigned Quals,
1449                                 RefQualifierKind RefQualifier,
1450                                 SourceLocation Loc, DeclarationName Entity,
1451                                 FunctionType::ExtInfo Info) {
1452  if (T->isArrayType() || T->isFunctionType()) {
1453    Diag(Loc, diag::err_func_returning_array_function)
1454      << T->isFunctionType() << T;
1455    return QualType();
1456  }
1457
1458  // Functions cannot return half FP.
1459  if (T->isHalfType()) {
1460    Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1461      FixItHint::CreateInsertion(Loc, "*");
1462    return QualType();
1463  }
1464
1465  bool Invalid = false;
1466  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
1467    // FIXME: Loc is too inprecise here, should use proper locations for args.
1468    QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1469    if (ParamType->isVoidType()) {
1470      Diag(Loc, diag::err_param_with_void_type);
1471      Invalid = true;
1472    } else if (ParamType->isHalfType()) {
1473      // Disallow half FP arguments.
1474      Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1475        FixItHint::CreateInsertion(Loc, "*");
1476      Invalid = true;
1477    }
1478
1479    ParamTypes[Idx] = ParamType;
1480  }
1481
1482  if (Invalid)
1483    return QualType();
1484
1485  FunctionProtoType::ExtProtoInfo EPI;
1486  EPI.Variadic = Variadic;
1487  EPI.TypeQuals = Quals;
1488  EPI.RefQualifier = RefQualifier;
1489  EPI.ExtInfo = Info;
1490
1491  return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
1492}
1493
1494/// \brief Build a member pointer type \c T Class::*.
1495///
1496/// \param T the type to which the member pointer refers.
1497/// \param Class the class type into which the member pointer points.
1498/// \param CVR Qualifiers applied to the member pointer type
1499/// \param Loc the location where this type begins
1500/// \param Entity the name of the entity that will have this member pointer type
1501///
1502/// \returns a member pointer type, if successful, or a NULL type if there was
1503/// an error.
1504QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1505                                      SourceLocation Loc,
1506                                      DeclarationName Entity) {
1507  // Verify that we're not building a pointer to pointer to function with
1508  // exception specification.
1509  if (CheckDistantExceptionSpec(T)) {
1510    Diag(Loc, diag::err_distant_exception_spec);
1511
1512    // FIXME: If we're doing this as part of template instantiation,
1513    // we should return immediately.
1514
1515    // Build the type anyway, but use the canonical type so that the
1516    // exception specifiers are stripped off.
1517    T = Context.getCanonicalType(T);
1518  }
1519
1520  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1521  //   with reference type, or "cv void."
1522  if (T->isReferenceType()) {
1523    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1524      << (Entity? Entity.getAsString() : "type name") << T;
1525    return QualType();
1526  }
1527
1528  if (T->isVoidType()) {
1529    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1530      << (Entity? Entity.getAsString() : "type name");
1531    return QualType();
1532  }
1533
1534  if (!Class->isDependentType() && !Class->isRecordType()) {
1535    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1536    return QualType();
1537  }
1538
1539  // In the Microsoft ABI, the class is allowed to be an incomplete
1540  // type. In such cases, the compiler makes a worst-case assumption.
1541  // We make no such assumption right now, so emit an error if the
1542  // class isn't a complete type.
1543  if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
1544      RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1545    return QualType();
1546
1547  return Context.getMemberPointerType(T, Class.getTypePtr());
1548}
1549
1550/// \brief Build a block pointer type.
1551///
1552/// \param T The type to which we'll be building a block pointer.
1553///
1554/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
1555///
1556/// \param Loc The location of the entity whose type involves this
1557/// block pointer type or, if there is no such entity, the location of the
1558/// type that will have block pointer type.
1559///
1560/// \param Entity The name of the entity that involves the block pointer
1561/// type, if known.
1562///
1563/// \returns A suitable block pointer type, if there are no
1564/// errors. Otherwise, returns a NULL type.
1565QualType Sema::BuildBlockPointerType(QualType T,
1566                                     SourceLocation Loc,
1567                                     DeclarationName Entity) {
1568  if (!T->isFunctionType()) {
1569    Diag(Loc, diag::err_nonfunction_block_type);
1570    return QualType();
1571  }
1572
1573  return Context.getBlockPointerType(T);
1574}
1575
1576QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1577  QualType QT = Ty.get();
1578  if (QT.isNull()) {
1579    if (TInfo) *TInfo = 0;
1580    return QualType();
1581  }
1582
1583  TypeSourceInfo *DI = 0;
1584  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1585    QT = LIT->getType();
1586    DI = LIT->getTypeSourceInfo();
1587  }
1588
1589  if (TInfo) *TInfo = DI;
1590  return QT;
1591}
1592
1593static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1594                                            Qualifiers::ObjCLifetime ownership,
1595                                            unsigned chunkIndex);
1596
1597/// Given that this is the declaration of a parameter under ARC,
1598/// attempt to infer attributes and such for pointer-to-whatever
1599/// types.
1600static void inferARCWriteback(TypeProcessingState &state,
1601                              QualType &declSpecType) {
1602  Sema &S = state.getSema();
1603  Declarator &declarator = state.getDeclarator();
1604
1605  // TODO: should we care about decl qualifiers?
1606
1607  // Check whether the declarator has the expected form.  We walk
1608  // from the inside out in order to make the block logic work.
1609  unsigned outermostPointerIndex = 0;
1610  bool isBlockPointer = false;
1611  unsigned numPointers = 0;
1612  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1613    unsigned chunkIndex = i;
1614    DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1615    switch (chunk.Kind) {
1616    case DeclaratorChunk::Paren:
1617      // Ignore parens.
1618      break;
1619
1620    case DeclaratorChunk::Reference:
1621    case DeclaratorChunk::Pointer:
1622      // Count the number of pointers.  Treat references
1623      // interchangeably as pointers; if they're mis-ordered, normal
1624      // type building will discover that.
1625      outermostPointerIndex = chunkIndex;
1626      numPointers++;
1627      break;
1628
1629    case DeclaratorChunk::BlockPointer:
1630      // If we have a pointer to block pointer, that's an acceptable
1631      // indirect reference; anything else is not an application of
1632      // the rules.
1633      if (numPointers != 1) return;
1634      numPointers++;
1635      outermostPointerIndex = chunkIndex;
1636      isBlockPointer = true;
1637
1638      // We don't care about pointer structure in return values here.
1639      goto done;
1640
1641    case DeclaratorChunk::Array: // suppress if written (id[])?
1642    case DeclaratorChunk::Function:
1643    case DeclaratorChunk::MemberPointer:
1644      return;
1645    }
1646  }
1647 done:
1648
1649  // If we have *one* pointer, then we want to throw the qualifier on
1650  // the declaration-specifiers, which means that it needs to be a
1651  // retainable object type.
1652  if (numPointers == 1) {
1653    // If it's not a retainable object type, the rule doesn't apply.
1654    if (!declSpecType->isObjCRetainableType()) return;
1655
1656    // If it already has lifetime, don't do anything.
1657    if (declSpecType.getObjCLifetime()) return;
1658
1659    // Otherwise, modify the type in-place.
1660    Qualifiers qs;
1661
1662    if (declSpecType->isObjCARCImplicitlyUnretainedType())
1663      qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1664    else
1665      qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1666    declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1667
1668  // If we have *two* pointers, then we want to throw the qualifier on
1669  // the outermost pointer.
1670  } else if (numPointers == 2) {
1671    // If we don't have a block pointer, we need to check whether the
1672    // declaration-specifiers gave us something that will turn into a
1673    // retainable object pointer after we slap the first pointer on it.
1674    if (!isBlockPointer && !declSpecType->isObjCObjectType())
1675      return;
1676
1677    // Look for an explicit lifetime attribute there.
1678    DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1679    if (chunk.Kind != DeclaratorChunk::Pointer &&
1680        chunk.Kind != DeclaratorChunk::BlockPointer)
1681      return;
1682    for (const AttributeList *attr = chunk.getAttrs(); attr;
1683           attr = attr->getNext())
1684      if (attr->getKind() == AttributeList::AT_objc_ownership)
1685        return;
1686
1687    transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1688                                          outermostPointerIndex);
1689
1690  // Any other number of pointers/references does not trigger the rule.
1691  } else return;
1692
1693  // TODO: mark whether we did this inference?
1694}
1695
1696static void DiagnoseIgnoredQualifiers(unsigned Quals,
1697                                      SourceLocation ConstQualLoc,
1698                                      SourceLocation VolatileQualLoc,
1699                                      SourceLocation RestrictQualLoc,
1700                                      Sema& S) {
1701  std::string QualStr;
1702  unsigned NumQuals = 0;
1703  SourceLocation Loc;
1704
1705  FixItHint ConstFixIt;
1706  FixItHint VolatileFixIt;
1707  FixItHint RestrictFixIt;
1708
1709  const SourceManager &SM = S.getSourceManager();
1710
1711  // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1712  // find a range and grow it to encompass all the qualifiers, regardless of
1713  // the order in which they textually appear.
1714  if (Quals & Qualifiers::Const) {
1715    ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
1716    QualStr = "const";
1717    ++NumQuals;
1718    if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1719      Loc = ConstQualLoc;
1720  }
1721  if (Quals & Qualifiers::Volatile) {
1722    VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
1723    QualStr += (NumQuals == 0 ? "volatile" : " volatile");
1724    ++NumQuals;
1725    if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1726      Loc = VolatileQualLoc;
1727  }
1728  if (Quals & Qualifiers::Restrict) {
1729    RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
1730    QualStr += (NumQuals == 0 ? "restrict" : " restrict");
1731    ++NumQuals;
1732    if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1733      Loc = RestrictQualLoc;
1734  }
1735
1736  assert(NumQuals > 0 && "No known qualifiers?");
1737
1738  S.Diag(Loc, diag::warn_qual_return_type)
1739    << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
1740}
1741
1742static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1743                                             TypeSourceInfo *&ReturnTypeInfo) {
1744  Sema &SemaRef = state.getSema();
1745  Declarator &D = state.getDeclarator();
1746  QualType T;
1747  ReturnTypeInfo = 0;
1748
1749  // The TagDecl owned by the DeclSpec.
1750  TagDecl *OwnedTagDecl = 0;
1751
1752  switch (D.getName().getKind()) {
1753  case UnqualifiedId::IK_ImplicitSelfParam:
1754  case UnqualifiedId::IK_OperatorFunctionId:
1755  case UnqualifiedId::IK_Identifier:
1756  case UnqualifiedId::IK_LiteralOperatorId:
1757  case UnqualifiedId::IK_TemplateId:
1758    T = ConvertDeclSpecToType(state);
1759
1760    if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
1761      OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1762      // Owned declaration is embedded in declarator.
1763      OwnedTagDecl->setEmbeddedInDeclarator(true);
1764    }
1765    break;
1766
1767  case UnqualifiedId::IK_ConstructorName:
1768  case UnqualifiedId::IK_ConstructorTemplateId:
1769  case UnqualifiedId::IK_DestructorName:
1770    // Constructors and destructors don't have return types. Use
1771    // "void" instead.
1772    T = SemaRef.Context.VoidTy;
1773    break;
1774
1775  case UnqualifiedId::IK_ConversionFunctionId:
1776    // The result type of a conversion function is the type that it
1777    // converts to.
1778    T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
1779                                  &ReturnTypeInfo);
1780    break;
1781  }
1782
1783  if (D.getAttributes())
1784    distributeTypeAttrsFromDeclarator(state, T);
1785
1786  // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1787  // In C++0x, a function declarator using 'auto' must have a trailing return
1788  // type (this is checked later) and we can skip this. In other languages
1789  // using auto, we need to check regardless.
1790  if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1791      (!SemaRef.getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
1792    int Error = -1;
1793
1794    switch (D.getContext()) {
1795    case Declarator::KNRTypeListContext:
1796      llvm_unreachable("K&R type lists aren't allowed in C++");
1797      break;
1798    case Declarator::LambdaExprContext:
1799      llvm_unreachable("Can't specify a type specifier in lambda grammar");
1800      break;
1801    case Declarator::ObjCParameterContext:
1802    case Declarator::ObjCResultContext:
1803    case Declarator::PrototypeContext:
1804      Error = 0; // Function prototype
1805      break;
1806    case Declarator::MemberContext:
1807      if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1808        break;
1809      switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
1810      case TTK_Enum: llvm_unreachable("unhandled tag kind");
1811      case TTK_Struct: Error = 1; /* Struct member */ break;
1812      case TTK_Union:  Error = 2; /* Union member */ break;
1813      case TTK_Class:  Error = 3; /* Class member */ break;
1814      }
1815      break;
1816    case Declarator::CXXCatchContext:
1817    case Declarator::ObjCCatchContext:
1818      Error = 4; // Exception declaration
1819      break;
1820    case Declarator::TemplateParamContext:
1821      Error = 5; // Template parameter
1822      break;
1823    case Declarator::BlockLiteralContext:
1824      Error = 6; // Block literal
1825      break;
1826    case Declarator::TemplateTypeArgContext:
1827      Error = 7; // Template type argument
1828      break;
1829    case Declarator::AliasDeclContext:
1830    case Declarator::AliasTemplateContext:
1831      Error = 9; // Type alias
1832      break;
1833    case Declarator::TypeNameContext:
1834      Error = 11; // Generic
1835      break;
1836    case Declarator::FileContext:
1837    case Declarator::BlockContext:
1838    case Declarator::ForContext:
1839    case Declarator::ConditionContext:
1840    case Declarator::CXXNewContext:
1841      break;
1842    }
1843
1844    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1845      Error = 8;
1846
1847    // In Objective-C it is an error to use 'auto' on a function declarator.
1848    if (D.isFunctionDeclarator())
1849      Error = 10;
1850
1851    // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1852    // contains a trailing return type. That is only legal at the outermost
1853    // level. Check all declarator chunks (outermost first) anyway, to give
1854    // better diagnostics.
1855    if (SemaRef.getLangOptions().CPlusPlus0x && Error != -1) {
1856      for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1857        unsigned chunkIndex = e - i - 1;
1858        state.setCurrentChunkIndex(chunkIndex);
1859        DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1860        if (DeclType.Kind == DeclaratorChunk::Function) {
1861          const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1862          if (FTI.TrailingReturnType) {
1863            Error = -1;
1864            break;
1865          }
1866        }
1867      }
1868    }
1869
1870    if (Error != -1) {
1871      SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1872                   diag::err_auto_not_allowed)
1873        << Error;
1874      T = SemaRef.Context.IntTy;
1875      D.setInvalidType(true);
1876    } else
1877      SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1878                   diag::warn_cxx98_compat_auto_type_specifier);
1879  }
1880
1881  if (SemaRef.getLangOptions().CPlusPlus &&
1882      OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
1883    // Check the contexts where C++ forbids the declaration of a new class
1884    // or enumeration in a type-specifier-seq.
1885    switch (D.getContext()) {
1886    case Declarator::FileContext:
1887    case Declarator::MemberContext:
1888    case Declarator::BlockContext:
1889    case Declarator::ForContext:
1890    case Declarator::BlockLiteralContext:
1891    case Declarator::LambdaExprContext:
1892      // C++0x [dcl.type]p3:
1893      //   A type-specifier-seq shall not define a class or enumeration unless
1894      //   it appears in the type-id of an alias-declaration (7.1.3) that is not
1895      //   the declaration of a template-declaration.
1896    case Declarator::AliasDeclContext:
1897      break;
1898    case Declarator::AliasTemplateContext:
1899      SemaRef.Diag(OwnedTagDecl->getLocation(),
1900             diag::err_type_defined_in_alias_template)
1901        << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1902      break;
1903    case Declarator::TypeNameContext:
1904    case Declarator::TemplateParamContext:
1905    case Declarator::CXXNewContext:
1906    case Declarator::CXXCatchContext:
1907    case Declarator::ObjCCatchContext:
1908    case Declarator::TemplateTypeArgContext:
1909      SemaRef.Diag(OwnedTagDecl->getLocation(),
1910             diag::err_type_defined_in_type_specifier)
1911        << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1912      break;
1913    case Declarator::PrototypeContext:
1914    case Declarator::ObjCParameterContext:
1915    case Declarator::ObjCResultContext:
1916    case Declarator::KNRTypeListContext:
1917      // C++ [dcl.fct]p6:
1918      //   Types shall not be defined in return or parameter types.
1919      SemaRef.Diag(OwnedTagDecl->getLocation(),
1920                   diag::err_type_defined_in_param_type)
1921        << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1922      break;
1923    case Declarator::ConditionContext:
1924      // C++ 6.4p2:
1925      // The type-specifier-seq shall not contain typedef and shall not declare
1926      // a new class or enumeration.
1927      SemaRef.Diag(OwnedTagDecl->getLocation(),
1928                   diag::err_type_defined_in_condition);
1929      break;
1930    }
1931  }
1932
1933  return T;
1934}
1935
1936static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
1937                                                QualType declSpecType,
1938                                                TypeSourceInfo *TInfo) {
1939
1940  QualType T = declSpecType;
1941  Declarator &D = state.getDeclarator();
1942  Sema &S = state.getSema();
1943  ASTContext &Context = S.Context;
1944  const LangOptions &LangOpts = S.getLangOptions();
1945
1946  bool ImplicitlyNoexcept = false;
1947  if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
1948      LangOpts.CPlusPlus0x) {
1949    OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1950    /// In C++0x, deallocation functions (normal and array operator delete)
1951    /// are implicitly noexcept.
1952    if (OO == OO_Delete || OO == OO_Array_Delete)
1953      ImplicitlyNoexcept = true;
1954  }
1955
1956  // The name we're declaring, if any.
1957  DeclarationName Name;
1958  if (D.getIdentifier())
1959    Name = D.getIdentifier();
1960
1961  // Does this declaration declare a typedef-name?
1962  bool IsTypedefName =
1963    D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
1964    D.getContext() == Declarator::AliasDeclContext ||
1965    D.getContext() == Declarator::AliasTemplateContext;
1966
1967  // Walk the DeclTypeInfo, building the recursive type as we go.
1968  // DeclTypeInfos are ordered from the identifier out, which is
1969  // opposite of what we want :).
1970  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1971    unsigned chunkIndex = e - i - 1;
1972    state.setCurrentChunkIndex(chunkIndex);
1973    DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1974    switch (DeclType.Kind) {
1975    case DeclaratorChunk::Paren:
1976      T = S.BuildParenType(T);
1977      break;
1978    case DeclaratorChunk::BlockPointer:
1979      // If blocks are disabled, emit an error.
1980      if (!LangOpts.Blocks)
1981        S.Diag(DeclType.Loc, diag::err_blocks_disable);
1982
1983      T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
1984      if (DeclType.Cls.TypeQuals)
1985        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
1986      break;
1987    case DeclaratorChunk::Pointer:
1988      // Verify that we're not building a pointer to pointer to function with
1989      // exception specification.
1990      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1991        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1992        D.setInvalidType(true);
1993        // Build the type anyway.
1994      }
1995      if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
1996        T = Context.getObjCObjectPointerType(T);
1997        if (DeclType.Ptr.TypeQuals)
1998          T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1999        break;
2000      }
2001      T = S.BuildPointerType(T, DeclType.Loc, Name);
2002      if (DeclType.Ptr.TypeQuals)
2003        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2004
2005      break;
2006    case DeclaratorChunk::Reference: {
2007      // Verify that we're not building a reference to pointer to function with
2008      // exception specification.
2009      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2010        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2011        D.setInvalidType(true);
2012        // Build the type anyway.
2013      }
2014      T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
2015
2016      Qualifiers Quals;
2017      if (DeclType.Ref.HasRestrict)
2018        T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
2019      break;
2020    }
2021    case DeclaratorChunk::Array: {
2022      // Verify that we're not building an array of pointers to function with
2023      // exception specification.
2024      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2025        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2026        D.setInvalidType(true);
2027        // Build the type anyway.
2028      }
2029      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
2030      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
2031      ArrayType::ArraySizeModifier ASM;
2032      if (ATI.isStar)
2033        ASM = ArrayType::Star;
2034      else if (ATI.hasStatic)
2035        ASM = ArrayType::Static;
2036      else
2037        ASM = ArrayType::Normal;
2038      if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
2039        // FIXME: This check isn't quite right: it allows star in prototypes
2040        // for function definitions, and disallows some edge cases detailed
2041        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
2042        S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
2043        ASM = ArrayType::Normal;
2044        D.setInvalidType(true);
2045      }
2046      T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
2047                           SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2048      break;
2049    }
2050    case DeclaratorChunk::Function: {
2051      // If the function declarator has a prototype (i.e. it is not () and
2052      // does not have a K&R-style identifier list), then the arguments are part
2053      // of the type, otherwise the argument list is ().
2054      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2055
2056      // Check for auto functions and trailing return type and adjust the
2057      // return type accordingly.
2058      if (!D.isInvalidType()) {
2059        // trailing-return-type is only required if we're declaring a function,
2060        // and not, for instance, a pointer to a function.
2061        if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2062            !FTI.TrailingReturnType && chunkIndex == 0) {
2063          S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2064               diag::err_auto_missing_trailing_return);
2065          T = Context.IntTy;
2066          D.setInvalidType(true);
2067        } else if (FTI.TrailingReturnType) {
2068          // T must be exactly 'auto' at this point. See CWG issue 681.
2069          if (isa<ParenType>(T)) {
2070            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2071                 diag::err_trailing_return_in_parens)
2072              << T << D.getDeclSpec().getSourceRange();
2073            D.setInvalidType(true);
2074          } else if (D.getContext() != Declarator::LambdaExprContext &&
2075                     (T.hasQualifiers() || !isa<AutoType>(T))) {
2076            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2077                 diag::err_trailing_return_without_auto)
2078              << T << D.getDeclSpec().getSourceRange();
2079            D.setInvalidType(true);
2080          }
2081
2082          T = S.GetTypeFromParser(
2083            ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
2084            &TInfo);
2085        }
2086      }
2087
2088      // C99 6.7.5.3p1: The return type may not be a function or array type.
2089      // For conversion functions, we'll diagnose this particular error later.
2090      if ((T->isArrayType() || T->isFunctionType()) &&
2091          (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2092        unsigned diagID = diag::err_func_returning_array_function;
2093        // Last processing chunk in block context means this function chunk
2094        // represents the block.
2095        if (chunkIndex == 0 &&
2096            D.getContext() == Declarator::BlockLiteralContext)
2097          diagID = diag::err_block_returning_array_function;
2098        S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2099        T = Context.IntTy;
2100        D.setInvalidType(true);
2101      }
2102
2103      // Do not allow returning half FP value.
2104      // FIXME: This really should be in BuildFunctionType.
2105      if (T->isHalfType()) {
2106        S.Diag(D.getIdentifierLoc(),
2107             diag::err_parameters_retval_cannot_have_fp16_type) << 1
2108          << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
2109        D.setInvalidType(true);
2110      }
2111
2112      // cv-qualifiers on return types are pointless except when the type is a
2113      // class type in C++.
2114      if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
2115          (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
2116          (!LangOpts.CPlusPlus || !T->isDependentType())) {
2117        assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2118        DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2119        assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2120
2121        DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2122
2123        DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2124            SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2125            SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2126            SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2127            S);
2128
2129      } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
2130          (!LangOpts.CPlusPlus ||
2131           (!T->isDependentType() && !T->isRecordType()))) {
2132
2133        DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2134                                  D.getDeclSpec().getConstSpecLoc(),
2135                                  D.getDeclSpec().getVolatileSpecLoc(),
2136                                  D.getDeclSpec().getRestrictSpecLoc(),
2137                                  S);
2138      }
2139
2140      if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
2141        // C++ [dcl.fct]p6:
2142        //   Types shall not be defined in return or parameter types.
2143        TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2144        if (Tag->isCompleteDefinition())
2145          S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2146            << Context.getTypeDeclType(Tag);
2147      }
2148
2149      // Exception specs are not allowed in typedefs. Complain, but add it
2150      // anyway.
2151      if (IsTypedefName && FTI.getExceptionSpecType())
2152        S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2153          << (D.getContext() == Declarator::AliasDeclContext ||
2154              D.getContext() == Declarator::AliasTemplateContext);
2155
2156      if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2157        // Simple void foo(), where the incoming T is the result type.
2158        T = Context.getFunctionNoProtoType(T);
2159      } else {
2160        // We allow a zero-parameter variadic function in C if the
2161        // function is marked with the "overloadable" attribute. Scan
2162        // for this attribute now.
2163        if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
2164          bool Overloadable = false;
2165          for (const AttributeList *Attrs = D.getAttributes();
2166               Attrs; Attrs = Attrs->getNext()) {
2167            if (Attrs->getKind() == AttributeList::AT_overloadable) {
2168              Overloadable = true;
2169              break;
2170            }
2171          }
2172
2173          if (!Overloadable)
2174            S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
2175        }
2176
2177        if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
2178          // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2179          // definition.
2180          S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
2181          D.setInvalidType(true);
2182          break;
2183        }
2184
2185        FunctionProtoType::ExtProtoInfo EPI;
2186        EPI.Variadic = FTI.isVariadic;
2187        EPI.TypeQuals = FTI.TypeQuals;
2188        EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2189                    : FTI.RefQualifierIsLValueRef? RQ_LValue
2190                    : RQ_RValue;
2191
2192        // Otherwise, we have a function with an argument list that is
2193        // potentially variadic.
2194        SmallVector<QualType, 16> ArgTys;
2195        ArgTys.reserve(FTI.NumArgs);
2196
2197        SmallVector<bool, 16> ConsumedArguments;
2198        ConsumedArguments.reserve(FTI.NumArgs);
2199        bool HasAnyConsumedArguments = false;
2200
2201        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2202          ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2203          QualType ArgTy = Param->getType();
2204          assert(!ArgTy.isNull() && "Couldn't parse type?");
2205
2206          // Adjust the parameter type.
2207          assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2208                 "Unadjusted type?");
2209
2210          // Look for 'void'.  void is allowed only as a single argument to a
2211          // function with no other parameters (C99 6.7.5.3p10).  We record
2212          // int(void) as a FunctionProtoType with an empty argument list.
2213          if (ArgTy->isVoidType()) {
2214            // If this is something like 'float(int, void)', reject it.  'void'
2215            // is an incomplete type (C99 6.2.5p19) and function decls cannot
2216            // have arguments of incomplete type.
2217            if (FTI.NumArgs != 1 || FTI.isVariadic) {
2218              S.Diag(DeclType.Loc, diag::err_void_only_param);
2219              ArgTy = Context.IntTy;
2220              Param->setType(ArgTy);
2221            } else if (FTI.ArgInfo[i].Ident) {
2222              // Reject, but continue to parse 'int(void abc)'.
2223              S.Diag(FTI.ArgInfo[i].IdentLoc,
2224                   diag::err_param_with_void_type);
2225              ArgTy = Context.IntTy;
2226              Param->setType(ArgTy);
2227            } else {
2228              // Reject, but continue to parse 'float(const void)'.
2229              if (ArgTy.hasQualifiers())
2230                S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2231
2232              // Do not add 'void' to the ArgTys list.
2233              break;
2234            }
2235          } else if (ArgTy->isHalfType()) {
2236            // Disallow half FP arguments.
2237            // FIXME: This really should be in BuildFunctionType.
2238            S.Diag(Param->getLocation(),
2239               diag::err_parameters_retval_cannot_have_fp16_type) << 0
2240            << FixItHint::CreateInsertion(Param->getLocation(), "*");
2241            D.setInvalidType();
2242          } else if (!FTI.hasPrototype) {
2243            if (ArgTy->isPromotableIntegerType()) {
2244              ArgTy = Context.getPromotedIntegerType(ArgTy);
2245              Param->setKNRPromoted(true);
2246            } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
2247              if (BTy->getKind() == BuiltinType::Float) {
2248                ArgTy = Context.DoubleTy;
2249                Param->setKNRPromoted(true);
2250              }
2251            }
2252          }
2253
2254          if (LangOpts.ObjCAutoRefCount) {
2255            bool Consumed = Param->hasAttr<NSConsumedAttr>();
2256            ConsumedArguments.push_back(Consumed);
2257            HasAnyConsumedArguments |= Consumed;
2258          }
2259
2260          ArgTys.push_back(ArgTy);
2261        }
2262
2263        if (HasAnyConsumedArguments)
2264          EPI.ConsumedArguments = ConsumedArguments.data();
2265
2266        SmallVector<QualType, 4> Exceptions;
2267        EPI.ExceptionSpecType = FTI.getExceptionSpecType();
2268        if (FTI.getExceptionSpecType() == EST_Dynamic) {
2269          Exceptions.reserve(FTI.NumExceptions);
2270          for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
2271            // FIXME: Preserve type source info.
2272            QualType ET = S.GetTypeFromParser(FTI.Exceptions[ei].Ty);
2273            // Check that the type is valid for an exception spec, and
2274            // drop it if not.
2275            if (!S.CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
2276              Exceptions.push_back(ET);
2277          }
2278          EPI.NumExceptions = Exceptions.size();
2279          EPI.Exceptions = Exceptions.data();
2280        } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
2281          // If an error occurred, there's no expression here.
2282          if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
2283            assert((NoexceptExpr->isTypeDependent() ||
2284                    NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
2285                        Context.BoolTy) &&
2286                 "Parser should have made sure that the expression is boolean");
2287            SourceLocation ErrLoc;
2288            llvm::APSInt Dummy;
2289            if (!NoexceptExpr->isValueDependent() &&
2290                !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
2291                                                     /*evaluated*/false))
2292              S.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
2293                  << NoexceptExpr->getSourceRange();
2294            else
2295              EPI.NoexceptExpr = NoexceptExpr;
2296          }
2297        } else if (FTI.getExceptionSpecType() == EST_None &&
2298                   ImplicitlyNoexcept && chunkIndex == 0) {
2299          // Only the outermost chunk is marked noexcept, of course.
2300          EPI.ExceptionSpecType = EST_BasicNoexcept;
2301        }
2302
2303        T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
2304      }
2305
2306      break;
2307    }
2308    case DeclaratorChunk::MemberPointer:
2309      // The scope spec must refer to a class, or be dependent.
2310      CXXScopeSpec &SS = DeclType.Mem.Scope();
2311      QualType ClsType;
2312      if (SS.isInvalid()) {
2313        // Avoid emitting extra errors if we already errored on the scope.
2314        D.setInvalidType(true);
2315      } else if (S.isDependentScopeSpecifier(SS) ||
2316                 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
2317        NestedNameSpecifier *NNS
2318          = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2319        NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2320        switch (NNS->getKind()) {
2321        case NestedNameSpecifier::Identifier:
2322          ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
2323                                                 NNS->getAsIdentifier());
2324          break;
2325
2326        case NestedNameSpecifier::Namespace:
2327        case NestedNameSpecifier::NamespaceAlias:
2328        case NestedNameSpecifier::Global:
2329          llvm_unreachable("Nested-name-specifier must name a type");
2330          break;
2331
2332        case NestedNameSpecifier::TypeSpec:
2333        case NestedNameSpecifier::TypeSpecWithTemplate:
2334          ClsType = QualType(NNS->getAsType(), 0);
2335          // Note: if the NNS has a prefix and ClsType is a nondependent
2336          // TemplateSpecializationType, then the NNS prefix is NOT included
2337          // in ClsType; hence we wrap ClsType into an ElaboratedType.
2338          // NOTE: in particular, no wrap occurs if ClsType already is an
2339          // Elaborated, DependentName, or DependentTemplateSpecialization.
2340          if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
2341            ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
2342          break;
2343        }
2344      } else {
2345        S.Diag(DeclType.Mem.Scope().getBeginLoc(),
2346             diag::err_illegal_decl_mempointer_in_nonclass)
2347          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2348          << DeclType.Mem.Scope().getRange();
2349        D.setInvalidType(true);
2350      }
2351
2352      if (!ClsType.isNull())
2353        T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
2354      if (T.isNull()) {
2355        T = Context.IntTy;
2356        D.setInvalidType(true);
2357      } else if (DeclType.Mem.TypeQuals) {
2358        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
2359      }
2360      break;
2361    }
2362
2363    if (T.isNull()) {
2364      D.setInvalidType(true);
2365      T = Context.IntTy;
2366    }
2367
2368    // See if there are any attributes on this declarator chunk.
2369    if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2370      processTypeAttrs(state, T, false, attrs);
2371  }
2372
2373  if (LangOpts.CPlusPlus && T->isFunctionType()) {
2374    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
2375    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
2376
2377    // C++ 8.3.5p4:
2378    //   A cv-qualifier-seq shall only be part of the function type
2379    //   for a nonstatic member function, the function type to which a pointer
2380    //   to member refers, or the top-level function type of a function typedef
2381    //   declaration.
2382    //
2383    // Core issue 547 also allows cv-qualifiers on function types that are
2384    // top-level template type arguments.
2385    bool FreeFunction;
2386    if (!D.getCXXScopeSpec().isSet()) {
2387      FreeFunction = ((D.getContext() != Declarator::MemberContext &&
2388                       D.getContext() != Declarator::LambdaExprContext) ||
2389                      D.getDeclSpec().isFriendSpecified());
2390    } else {
2391      DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
2392      FreeFunction = (DC && !DC->isRecord());
2393    }
2394
2395    // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
2396    // function that is not a constructor declares that function to be const.
2397    if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
2398        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static &&
2399        D.getName().getKind() != UnqualifiedId::IK_ConstructorName &&
2400        D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId &&
2401        !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
2402      // Rebuild function type adding a 'const' qualifier.
2403      FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2404      EPI.TypeQuals |= DeclSpec::TQ_const;
2405      T = Context.getFunctionType(FnTy->getResultType(),
2406                                  FnTy->arg_type_begin(),
2407                                  FnTy->getNumArgs(), EPI);
2408    }
2409
2410    // C++0x [dcl.fct]p6:
2411    //   A ref-qualifier shall only be part of the function type for a
2412    //   non-static member function, the function type to which a pointer to
2413    //   member refers, or the top-level function type of a function typedef
2414    //   declaration.
2415    if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
2416        !(D.getContext() == Declarator::TemplateTypeArgContext &&
2417          !D.isFunctionDeclarator()) && !IsTypedefName &&
2418        (FreeFunction ||
2419         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
2420      if (D.getContext() == Declarator::TemplateTypeArgContext) {
2421        // Accept qualified function types as template type arguments as a GNU
2422        // extension. This is also the subject of C++ core issue 547.
2423        std::string Quals;
2424        if (FnTy->getTypeQuals() != 0)
2425          Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2426
2427        switch (FnTy->getRefQualifier()) {
2428        case RQ_None:
2429          break;
2430
2431        case RQ_LValue:
2432          if (!Quals.empty())
2433            Quals += ' ';
2434          Quals += '&';
2435          break;
2436
2437        case RQ_RValue:
2438          if (!Quals.empty())
2439            Quals += ' ';
2440          Quals += "&&";
2441          break;
2442        }
2443
2444        S.Diag(D.getIdentifierLoc(),
2445             diag::ext_qualified_function_type_template_arg)
2446          << Quals;
2447      } else {
2448        if (FnTy->getTypeQuals() != 0) {
2449          if (D.isFunctionDeclarator()) {
2450            SourceRange Range = D.getIdentifierLoc();
2451            for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2452              const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2453              if (Chunk.Kind == DeclaratorChunk::Function &&
2454                  Chunk.Fun.TypeQuals != 0) {
2455                switch (Chunk.Fun.TypeQuals) {
2456                case Qualifiers::Const:
2457                  Range = Chunk.Fun.getConstQualifierLoc();
2458                  break;
2459                case Qualifiers::Volatile:
2460                  Range = Chunk.Fun.getVolatileQualifierLoc();
2461                  break;
2462                case Qualifiers::Const | Qualifiers::Volatile: {
2463                    SourceLocation CLoc = Chunk.Fun.getConstQualifierLoc();
2464                    SourceLocation VLoc = Chunk.Fun.getVolatileQualifierLoc();
2465                    if (S.getSourceManager()
2466                        .isBeforeInTranslationUnit(CLoc, VLoc)) {
2467                      Range = SourceRange(CLoc, VLoc);
2468                    } else {
2469                      Range = SourceRange(VLoc, CLoc);
2470                    }
2471                  }
2472                  break;
2473                }
2474                break;
2475              }
2476            }
2477            S.Diag(Range.getBegin(), diag::err_invalid_qualified_function_type)
2478                << FixItHint::CreateRemoval(Range);
2479          } else
2480            S.Diag(D.getIdentifierLoc(),
2481                 diag::err_invalid_qualified_typedef_function_type_use)
2482              << FreeFunction;
2483        }
2484
2485        if (FnTy->getRefQualifier()) {
2486          if (D.isFunctionDeclarator()) {
2487            SourceLocation Loc = D.getIdentifierLoc();
2488            for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2489              const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2490              if (Chunk.Kind == DeclaratorChunk::Function &&
2491                  Chunk.Fun.hasRefQualifier()) {
2492                Loc = Chunk.Fun.getRefQualifierLoc();
2493                break;
2494              }
2495            }
2496
2497            S.Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
2498              << (FnTy->getRefQualifier() == RQ_LValue)
2499              << FixItHint::CreateRemoval(Loc);
2500          } else {
2501            S.Diag(D.getIdentifierLoc(),
2502                 diag::err_invalid_ref_qualifier_typedef_function_type_use)
2503              << FreeFunction
2504              << (FnTy->getRefQualifier() == RQ_LValue);
2505          }
2506        }
2507
2508        // Strip the cv-qualifiers and ref-qualifiers from the type.
2509        FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2510        EPI.TypeQuals = 0;
2511        EPI.RefQualifier = RQ_None;
2512
2513        T = Context.getFunctionType(FnTy->getResultType(),
2514                                    FnTy->arg_type_begin(),
2515                                    FnTy->getNumArgs(), EPI);
2516      }
2517    }
2518  }
2519
2520  // Apply any undistributed attributes from the declarator.
2521  if (!T.isNull())
2522    if (AttributeList *attrs = D.getAttributes())
2523      processTypeAttrs(state, T, false, attrs);
2524
2525  // Diagnose any ignored type attributes.
2526  if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2527
2528  // C++0x [dcl.constexpr]p9:
2529  //  A constexpr specifier used in an object declaration declares the object
2530  //  as const.
2531  if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
2532    T.addConst();
2533  }
2534
2535  // If there was an ellipsis in the declarator, the declaration declares a
2536  // parameter pack whose type may be a pack expansion type.
2537  if (D.hasEllipsis() && !T.isNull()) {
2538    // C++0x [dcl.fct]p13:
2539    //   A declarator-id or abstract-declarator containing an ellipsis shall
2540    //   only be used in a parameter-declaration. Such a parameter-declaration
2541    //   is a parameter pack (14.5.3). [...]
2542    switch (D.getContext()) {
2543    case Declarator::PrototypeContext:
2544      // C++0x [dcl.fct]p13:
2545      //   [...] When it is part of a parameter-declaration-clause, the
2546      //   parameter pack is a function parameter pack (14.5.3). The type T
2547      //   of the declarator-id of the function parameter pack shall contain
2548      //   a template parameter pack; each template parameter pack in T is
2549      //   expanded by the function parameter pack.
2550      //
2551      // We represent function parameter packs as function parameters whose
2552      // type is a pack expansion.
2553      if (!T->containsUnexpandedParameterPack()) {
2554        S.Diag(D.getEllipsisLoc(),
2555             diag::err_function_parameter_pack_without_parameter_packs)
2556          << T <<  D.getSourceRange();
2557        D.setEllipsisLoc(SourceLocation());
2558      } else {
2559        T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2560      }
2561      break;
2562
2563    case Declarator::TemplateParamContext:
2564      // C++0x [temp.param]p15:
2565      //   If a template-parameter is a [...] is a parameter-declaration that
2566      //   declares a parameter pack (8.3.5), then the template-parameter is a
2567      //   template parameter pack (14.5.3).
2568      //
2569      // Note: core issue 778 clarifies that, if there are any unexpanded
2570      // parameter packs in the type of the non-type template parameter, then
2571      // it expands those parameter packs.
2572      if (T->containsUnexpandedParameterPack())
2573        T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2574      else
2575        S.Diag(D.getEllipsisLoc(),
2576               LangOpts.CPlusPlus0x
2577                 ? diag::warn_cxx98_compat_variadic_templates
2578                 : diag::ext_variadic_templates);
2579      break;
2580
2581    case Declarator::FileContext:
2582    case Declarator::KNRTypeListContext:
2583    case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
2584    case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
2585    case Declarator::TypeNameContext:
2586    case Declarator::CXXNewContext:
2587    case Declarator::AliasDeclContext:
2588    case Declarator::AliasTemplateContext:
2589    case Declarator::MemberContext:
2590    case Declarator::BlockContext:
2591    case Declarator::ForContext:
2592    case Declarator::ConditionContext:
2593    case Declarator::CXXCatchContext:
2594    case Declarator::ObjCCatchContext:
2595    case Declarator::BlockLiteralContext:
2596    case Declarator::LambdaExprContext:
2597    case Declarator::TemplateTypeArgContext:
2598      // FIXME: We may want to allow parameter packs in block-literal contexts
2599      // in the future.
2600      S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
2601      D.setEllipsisLoc(SourceLocation());
2602      break;
2603    }
2604  }
2605
2606  if (T.isNull())
2607    return Context.getNullTypeSourceInfo();
2608  else if (D.isInvalidType())
2609    return Context.getTrivialTypeSourceInfo(T);
2610
2611  return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2612}
2613
2614/// GetTypeForDeclarator - Convert the type for the specified
2615/// declarator to Type instances.
2616///
2617/// The result of this call will never be null, but the associated
2618/// type may be a null type if there's an unrecoverable error.
2619TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2620  // Determine the type of the declarator. Not all forms of declarator
2621  // have a type.
2622
2623  TypeProcessingState state(*this, D);
2624
2625  TypeSourceInfo *ReturnTypeInfo = 0;
2626  QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2627  if (T.isNull())
2628    return Context.getNullTypeSourceInfo();
2629
2630  if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount)
2631    inferARCWriteback(state, T);
2632
2633  return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
2634}
2635
2636static void transferARCOwnershipToDeclSpec(Sema &S,
2637                                           QualType &declSpecTy,
2638                                           Qualifiers::ObjCLifetime ownership) {
2639  if (declSpecTy->isObjCRetainableType() &&
2640      declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2641    Qualifiers qs;
2642    qs.addObjCLifetime(ownership);
2643    declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2644  }
2645}
2646
2647static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2648                                            Qualifiers::ObjCLifetime ownership,
2649                                            unsigned chunkIndex) {
2650  Sema &S = state.getSema();
2651  Declarator &D = state.getDeclarator();
2652
2653  // Look for an explicit lifetime attribute.
2654  DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2655  for (const AttributeList *attr = chunk.getAttrs(); attr;
2656         attr = attr->getNext())
2657    if (attr->getKind() == AttributeList::AT_objc_ownership)
2658      return;
2659
2660  const char *attrStr = 0;
2661  switch (ownership) {
2662  case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
2663  case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2664  case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2665  case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2666  case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2667  }
2668
2669  // If there wasn't one, add one (with an invalid source location
2670  // so that we don't make an AttributedType for it).
2671  AttributeList *attr = D.getAttributePool()
2672    .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2673            /*scope*/ 0, SourceLocation(),
2674            &S.Context.Idents.get(attrStr), SourceLocation(),
2675            /*args*/ 0, 0,
2676            /*declspec*/ false, /*C++0x*/ false);
2677  spliceAttrIntoList(*attr, chunk.getAttrListRef());
2678
2679  // TODO: mark whether we did this inference?
2680}
2681
2682/// \brief Used for transfering ownership in casts resulting in l-values.
2683static void transferARCOwnership(TypeProcessingState &state,
2684                                 QualType &declSpecTy,
2685                                 Qualifiers::ObjCLifetime ownership) {
2686  Sema &S = state.getSema();
2687  Declarator &D = state.getDeclarator();
2688
2689  int inner = -1;
2690  bool hasIndirection = false;
2691  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2692    DeclaratorChunk &chunk = D.getTypeObject(i);
2693    switch (chunk.Kind) {
2694    case DeclaratorChunk::Paren:
2695      // Ignore parens.
2696      break;
2697
2698    case DeclaratorChunk::Array:
2699    case DeclaratorChunk::Reference:
2700    case DeclaratorChunk::Pointer:
2701      if (inner != -1)
2702        hasIndirection = true;
2703      inner = i;
2704      break;
2705
2706    case DeclaratorChunk::BlockPointer:
2707      if (inner != -1)
2708        transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2709      return;
2710
2711    case DeclaratorChunk::Function:
2712    case DeclaratorChunk::MemberPointer:
2713      return;
2714    }
2715  }
2716
2717  if (inner == -1)
2718    return;
2719
2720  DeclaratorChunk &chunk = D.getTypeObject(inner);
2721  if (chunk.Kind == DeclaratorChunk::Pointer) {
2722    if (declSpecTy->isObjCRetainableType())
2723      return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2724    if (declSpecTy->isObjCObjectType() && hasIndirection)
2725      return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2726  } else {
2727    assert(chunk.Kind == DeclaratorChunk::Array ||
2728           chunk.Kind == DeclaratorChunk::Reference);
2729    return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2730  }
2731}
2732
2733TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2734  TypeProcessingState state(*this, D);
2735
2736  TypeSourceInfo *ReturnTypeInfo = 0;
2737  QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2738  if (declSpecTy.isNull())
2739    return Context.getNullTypeSourceInfo();
2740
2741  if (getLangOptions().ObjCAutoRefCount) {
2742    Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
2743    if (ownership != Qualifiers::OCL_None)
2744      transferARCOwnership(state, declSpecTy, ownership);
2745  }
2746
2747  return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
2748}
2749
2750/// Map an AttributedType::Kind to an AttributeList::Kind.
2751static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2752  switch (kind) {
2753  case AttributedType::attr_address_space:
2754    return AttributeList::AT_address_space;
2755  case AttributedType::attr_regparm:
2756    return AttributeList::AT_regparm;
2757  case AttributedType::attr_vector_size:
2758    return AttributeList::AT_vector_size;
2759  case AttributedType::attr_neon_vector_type:
2760    return AttributeList::AT_neon_vector_type;
2761  case AttributedType::attr_neon_polyvector_type:
2762    return AttributeList::AT_neon_polyvector_type;
2763  case AttributedType::attr_objc_gc:
2764    return AttributeList::AT_objc_gc;
2765  case AttributedType::attr_objc_ownership:
2766    return AttributeList::AT_objc_ownership;
2767  case AttributedType::attr_noreturn:
2768    return AttributeList::AT_noreturn;
2769  case AttributedType::attr_cdecl:
2770    return AttributeList::AT_cdecl;
2771  case AttributedType::attr_fastcall:
2772    return AttributeList::AT_fastcall;
2773  case AttributedType::attr_stdcall:
2774    return AttributeList::AT_stdcall;
2775  case AttributedType::attr_thiscall:
2776    return AttributeList::AT_thiscall;
2777  case AttributedType::attr_pascal:
2778    return AttributeList::AT_pascal;
2779  case AttributedType::attr_pcs:
2780    return AttributeList::AT_pcs;
2781  }
2782  llvm_unreachable("unexpected attribute kind!");
2783  return AttributeList::Kind();
2784}
2785
2786static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2787                                  const AttributeList *attrs) {
2788  AttributedType::Kind kind = TL.getAttrKind();
2789
2790  assert(attrs && "no type attributes in the expected location!");
2791  AttributeList::Kind parsedKind = getAttrListKind(kind);
2792  while (attrs->getKind() != parsedKind) {
2793    attrs = attrs->getNext();
2794    assert(attrs && "no matching attribute in expected location!");
2795  }
2796
2797  TL.setAttrNameLoc(attrs->getLoc());
2798  if (TL.hasAttrExprOperand())
2799    TL.setAttrExprOperand(attrs->getArg(0));
2800  else if (TL.hasAttrEnumOperand())
2801    TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2802
2803  // FIXME: preserve this information to here.
2804  if (TL.hasAttrOperand())
2805    TL.setAttrOperandParensRange(SourceRange());
2806}
2807
2808namespace {
2809  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
2810    ASTContext &Context;
2811    const DeclSpec &DS;
2812
2813  public:
2814    TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2815      : Context(Context), DS(DS) {}
2816
2817    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2818      fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2819      Visit(TL.getModifiedLoc());
2820    }
2821    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2822      Visit(TL.getUnqualifiedLoc());
2823    }
2824    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2825      TL.setNameLoc(DS.getTypeSpecTypeLoc());
2826    }
2827    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2828      TL.setNameLoc(DS.getTypeSpecTypeLoc());
2829    }
2830    void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2831      // Handle the base type, which might not have been written explicitly.
2832      if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2833        TL.setHasBaseTypeAsWritten(false);
2834        TL.getBaseLoc().initialize(Context, SourceLocation());
2835      } else {
2836        TL.setHasBaseTypeAsWritten(true);
2837        Visit(TL.getBaseLoc());
2838      }
2839
2840      // Protocol qualifiers.
2841      if (DS.getProtocolQualifiers()) {
2842        assert(TL.getNumProtocols() > 0);
2843        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2844        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2845        TL.setRAngleLoc(DS.getSourceRange().getEnd());
2846        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2847          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2848      } else {
2849        assert(TL.getNumProtocols() == 0);
2850        TL.setLAngleLoc(SourceLocation());
2851        TL.setRAngleLoc(SourceLocation());
2852      }
2853    }
2854    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2855      TL.setStarLoc(SourceLocation());
2856      Visit(TL.getPointeeLoc());
2857    }
2858    void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
2859      TypeSourceInfo *TInfo = 0;
2860      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2861
2862      // If we got no declarator info from previous Sema routines,
2863      // just fill with the typespec loc.
2864      if (!TInfo) {
2865        TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
2866        return;
2867      }
2868
2869      TypeLoc OldTL = TInfo->getTypeLoc();
2870      if (TInfo->getType()->getAs<ElaboratedType>()) {
2871        ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2872        TemplateSpecializationTypeLoc NamedTL =
2873          cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2874        TL.copy(NamedTL);
2875      }
2876      else
2877        TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
2878    }
2879    void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2880      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2881      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2882      TL.setParensRange(DS.getTypeofParensRange());
2883    }
2884    void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2885      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2886      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2887      TL.setParensRange(DS.getTypeofParensRange());
2888      assert(DS.getRepAsType());
2889      TypeSourceInfo *TInfo = 0;
2890      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2891      TL.setUnderlyingTInfo(TInfo);
2892    }
2893    void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2894      // FIXME: This holds only because we only have one unary transform.
2895      assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2896      TL.setKWLoc(DS.getTypeSpecTypeLoc());
2897      TL.setParensRange(DS.getTypeofParensRange());
2898      assert(DS.getRepAsType());
2899      TypeSourceInfo *TInfo = 0;
2900      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2901      TL.setUnderlyingTInfo(TInfo);
2902    }
2903    void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2904      // By default, use the source location of the type specifier.
2905      TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2906      if (TL.needsExtraLocalData()) {
2907        // Set info for the written builtin specifiers.
2908        TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2909        // Try to have a meaningful source location.
2910        if (TL.getWrittenSignSpec() != TSS_unspecified)
2911          // Sign spec loc overrides the others (e.g., 'unsigned long').
2912          TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2913        else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2914          // Width spec loc overrides type spec loc (e.g., 'short int').
2915          TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2916      }
2917    }
2918    void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2919      ElaboratedTypeKeyword Keyword
2920        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2921      if (DS.getTypeSpecType() == TST_typename) {
2922        TypeSourceInfo *TInfo = 0;
2923        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2924        if (TInfo) {
2925          TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2926          return;
2927        }
2928      }
2929      TL.setKeywordLoc(Keyword != ETK_None
2930                       ? DS.getTypeSpecTypeLoc()
2931                       : SourceLocation());
2932      const CXXScopeSpec& SS = DS.getTypeSpecScope();
2933      TL.setQualifierLoc(SS.getWithLocInContext(Context));
2934      Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2935    }
2936    void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2937      ElaboratedTypeKeyword Keyword
2938        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2939      if (DS.getTypeSpecType() == TST_typename) {
2940        TypeSourceInfo *TInfo = 0;
2941        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2942        if (TInfo) {
2943          TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2944          return;
2945        }
2946      }
2947      TL.setKeywordLoc(Keyword != ETK_None
2948                       ? DS.getTypeSpecTypeLoc()
2949                       : SourceLocation());
2950      const CXXScopeSpec& SS = DS.getTypeSpecScope();
2951      TL.setQualifierLoc(SS.getWithLocInContext(Context));
2952      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2953    }
2954    void VisitDependentTemplateSpecializationTypeLoc(
2955                                 DependentTemplateSpecializationTypeLoc TL) {
2956      ElaboratedTypeKeyword Keyword
2957        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2958      if (Keyword == ETK_Typename) {
2959        TypeSourceInfo *TInfo = 0;
2960        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2961        if (TInfo) {
2962          TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2963                    TInfo->getTypeLoc()));
2964          return;
2965        }
2966      }
2967      TL.initializeLocal(Context, SourceLocation());
2968      TL.setKeywordLoc(Keyword != ETK_None
2969                       ? DS.getTypeSpecTypeLoc()
2970                       : SourceLocation());
2971      const CXXScopeSpec& SS = DS.getTypeSpecScope();
2972      TL.setQualifierLoc(SS.getWithLocInContext(Context));
2973      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2974    }
2975    void VisitTagTypeLoc(TagTypeLoc TL) {
2976      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2977    }
2978    void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
2979      TL.setKWLoc(DS.getTypeSpecTypeLoc());
2980      TL.setParensRange(DS.getTypeofParensRange());
2981
2982      TypeSourceInfo *TInfo = 0;
2983      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2984      TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
2985    }
2986
2987    void VisitTypeLoc(TypeLoc TL) {
2988      // FIXME: add other typespec types and change this to an assert.
2989      TL.initialize(Context, DS.getTypeSpecTypeLoc());
2990    }
2991  };
2992
2993  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
2994    ASTContext &Context;
2995    const DeclaratorChunk &Chunk;
2996
2997  public:
2998    DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2999      : Context(Context), Chunk(Chunk) {}
3000
3001    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3002      llvm_unreachable("qualified type locs not expected here!");
3003    }
3004
3005    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3006      fillAttributedTypeLoc(TL, Chunk.getAttrs());
3007    }
3008    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3009      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3010      TL.setCaretLoc(Chunk.Loc);
3011    }
3012    void VisitPointerTypeLoc(PointerTypeLoc TL) {
3013      assert(Chunk.Kind == DeclaratorChunk::Pointer);
3014      TL.setStarLoc(Chunk.Loc);
3015    }
3016    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3017      assert(Chunk.Kind == DeclaratorChunk::Pointer);
3018      TL.setStarLoc(Chunk.Loc);
3019    }
3020    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3021      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
3022      const CXXScopeSpec& SS = Chunk.Mem.Scope();
3023      NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3024
3025      const Type* ClsTy = TL.getClass();
3026      QualType ClsQT = QualType(ClsTy, 0);
3027      TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3028      // Now copy source location info into the type loc component.
3029      TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3030      switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3031      case NestedNameSpecifier::Identifier:
3032        assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3033        {
3034          DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
3035          DNTLoc.setKeywordLoc(SourceLocation());
3036          DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3037          DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3038        }
3039        break;
3040
3041      case NestedNameSpecifier::TypeSpec:
3042      case NestedNameSpecifier::TypeSpecWithTemplate:
3043        if (isa<ElaboratedType>(ClsTy)) {
3044          ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
3045          ETLoc.setKeywordLoc(SourceLocation());
3046          ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3047          TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3048          NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3049        } else {
3050          ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3051        }
3052        break;
3053
3054      case NestedNameSpecifier::Namespace:
3055      case NestedNameSpecifier::NamespaceAlias:
3056      case NestedNameSpecifier::Global:
3057        llvm_unreachable("Nested-name-specifier must name a type");
3058        break;
3059      }
3060
3061      // Finally fill in MemberPointerLocInfo fields.
3062      TL.setStarLoc(Chunk.Loc);
3063      TL.setClassTInfo(ClsTInfo);
3064    }
3065    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3066      assert(Chunk.Kind == DeclaratorChunk::Reference);
3067      // 'Amp' is misleading: this might have been originally
3068      /// spelled with AmpAmp.
3069      TL.setAmpLoc(Chunk.Loc);
3070    }
3071    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3072      assert(Chunk.Kind == DeclaratorChunk::Reference);
3073      assert(!Chunk.Ref.LValueRef);
3074      TL.setAmpAmpLoc(Chunk.Loc);
3075    }
3076    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3077      assert(Chunk.Kind == DeclaratorChunk::Array);
3078      TL.setLBracketLoc(Chunk.Loc);
3079      TL.setRBracketLoc(Chunk.EndLoc);
3080      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3081    }
3082    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3083      assert(Chunk.Kind == DeclaratorChunk::Function);
3084      TL.setLocalRangeBegin(Chunk.Loc);
3085      TL.setLocalRangeEnd(Chunk.EndLoc);
3086      TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
3087
3088      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3089      for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
3090        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
3091        TL.setArg(tpi++, Param);
3092      }
3093      // FIXME: exception specs
3094    }
3095    void VisitParenTypeLoc(ParenTypeLoc TL) {
3096      assert(Chunk.Kind == DeclaratorChunk::Paren);
3097      TL.setLParenLoc(Chunk.Loc);
3098      TL.setRParenLoc(Chunk.EndLoc);
3099    }
3100
3101    void VisitTypeLoc(TypeLoc TL) {
3102      llvm_unreachable("unsupported TypeLoc kind in declarator!");
3103    }
3104  };
3105}
3106
3107/// \brief Create and instantiate a TypeSourceInfo with type source information.
3108///
3109/// \param T QualType referring to the type as written in source code.
3110///
3111/// \param ReturnTypeInfo For declarators whose return type does not show
3112/// up in the normal place in the declaration specifiers (such as a C++
3113/// conversion function), this pointer will refer to a type source information
3114/// for that return type.
3115TypeSourceInfo *
3116Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3117                                     TypeSourceInfo *ReturnTypeInfo) {
3118  TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3119  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3120
3121  // Handle parameter packs whose type is a pack expansion.
3122  if (isa<PackExpansionType>(T)) {
3123    cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
3124    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3125  }
3126
3127  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3128    while (isa<AttributedTypeLoc>(CurrTL)) {
3129      AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3130      fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3131      CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3132    }
3133
3134    DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3135    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3136  }
3137
3138  // If we have different source information for the return type, use
3139  // that.  This really only applies to C++ conversion functions.
3140  if (ReturnTypeInfo) {
3141    TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3142    assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3143    memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3144  } else {
3145    TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3146  }
3147
3148  return TInfo;
3149}
3150
3151/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
3152ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3153  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3154  // and Sema during declaration parsing. Try deallocating/caching them when
3155  // it's appropriate, instead of allocating them and keeping them around.
3156  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3157                                                       TypeAlignment);
3158  new (LocT) LocInfoType(T, TInfo);
3159  assert(LocT->getTypeClass() != T->getTypeClass() &&
3160         "LocInfoType's TypeClass conflicts with an existing Type class");
3161  return ParsedType::make(QualType(LocT, 0));
3162}
3163
3164void LocInfoType::getAsStringInternal(std::string &Str,
3165                                      const PrintingPolicy &Policy) const {
3166  llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3167         " was used directly instead of getting the QualType through"
3168         " GetTypeFromParser");
3169}
3170
3171TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3172  // C99 6.7.6: Type names have no identifier.  This is already validated by
3173  // the parser.
3174  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
3175
3176  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3177  QualType T = TInfo->getType();
3178  if (D.isInvalidType())
3179    return true;
3180
3181  // Make sure there are no unused decl attributes on the declarator.
3182  // We don't want to do this for ObjC parameters because we're going
3183  // to apply them to the actual parameter declaration.
3184  if (D.getContext() != Declarator::ObjCParameterContext)
3185    checkUnusedDeclAttributes(D);
3186
3187  if (getLangOptions().CPlusPlus) {
3188    // Check that there are no default arguments (C++ only).
3189    CheckExtraCXXDefaultArguments(D);
3190  }
3191
3192  return CreateParsedType(T, TInfo);
3193}
3194
3195ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3196  QualType T = Context.getObjCInstanceType();
3197  TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3198  return CreateParsedType(T, TInfo);
3199}
3200
3201
3202//===----------------------------------------------------------------------===//
3203// Type Attribute Processing
3204//===----------------------------------------------------------------------===//
3205
3206/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3207/// specified type.  The attribute contains 1 argument, the id of the address
3208/// space for the type.
3209static void HandleAddressSpaceTypeAttribute(QualType &Type,
3210                                            const AttributeList &Attr, Sema &S){
3211
3212  // If this type is already address space qualified, reject it.
3213  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3214  // qualifiers for two or more different address spaces."
3215  if (Type.getAddressSpace()) {
3216    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3217    Attr.setInvalid();
3218    return;
3219  }
3220
3221  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3222  // qualified by an address-space qualifier."
3223  if (Type->isFunctionType()) {
3224    S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3225    Attr.setInvalid();
3226    return;
3227  }
3228
3229  // Check the attribute arguments.
3230  if (Attr.getNumArgs() != 1) {
3231    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3232    Attr.setInvalid();
3233    return;
3234  }
3235  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3236  llvm::APSInt addrSpace(32);
3237  if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3238      !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3239    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3240      << ASArgExpr->getSourceRange();
3241    Attr.setInvalid();
3242    return;
3243  }
3244
3245  // Bounds checking.
3246  if (addrSpace.isSigned()) {
3247    if (addrSpace.isNegative()) {
3248      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3249        << ASArgExpr->getSourceRange();
3250      Attr.setInvalid();
3251      return;
3252    }
3253    addrSpace.setIsSigned(false);
3254  }
3255  llvm::APSInt max(addrSpace.getBitWidth());
3256  max = Qualifiers::MaxAddressSpace;
3257  if (addrSpace > max) {
3258    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3259      << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
3260    Attr.setInvalid();
3261    return;
3262  }
3263
3264  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3265  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3266}
3267
3268/// handleObjCOwnershipTypeAttr - Process an objc_ownership
3269/// attribute on the specified type.
3270///
3271/// Returns 'true' if the attribute was handled.
3272static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
3273                                       AttributeList &attr,
3274                                       QualType &type) {
3275  bool NonObjCPointer = false;
3276
3277  if (!type->isDependentType()) {
3278    if (const PointerType *ptr = type->getAs<PointerType>()) {
3279      QualType pointee = ptr->getPointeeType();
3280      if (pointee->isObjCRetainableType() || pointee->isPointerType())
3281        return false;
3282      // It is important not to lose the source info that there was an attribute
3283      // applied to non-objc pointer. We will create an attributed type but
3284      // its type will be the same as the original type.
3285      NonObjCPointer = true;
3286    } else if (!type->isObjCRetainableType()) {
3287      return false;
3288    }
3289  }
3290
3291  Sema &S = state.getSema();
3292  SourceLocation AttrLoc = attr.getLoc();
3293  if (AttrLoc.isMacroID())
3294    AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
3295
3296  if (type.getQualifiers().getObjCLifetime()) {
3297    S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3298      << type;
3299    return true;
3300  }
3301
3302  if (!attr.getParameterName()) {
3303    S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
3304      << "objc_ownership" << 1;
3305    attr.setInvalid();
3306    return true;
3307  }
3308
3309  Qualifiers::ObjCLifetime lifetime;
3310  if (attr.getParameterName()->isStr("none"))
3311    lifetime = Qualifiers::OCL_ExplicitNone;
3312  else if (attr.getParameterName()->isStr("strong"))
3313    lifetime = Qualifiers::OCL_Strong;
3314  else if (attr.getParameterName()->isStr("weak"))
3315    lifetime = Qualifiers::OCL_Weak;
3316  else if (attr.getParameterName()->isStr("autoreleasing"))
3317    lifetime = Qualifiers::OCL_Autoreleasing;
3318  else {
3319    S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
3320      << "objc_ownership" << attr.getParameterName();
3321    attr.setInvalid();
3322    return true;
3323  }
3324
3325  // Consume lifetime attributes without further comment outside of
3326  // ARC mode.
3327  if (!S.getLangOptions().ObjCAutoRefCount)
3328    return true;
3329
3330  if (NonObjCPointer) {
3331    StringRef name = attr.getName()->getName();
3332    switch (lifetime) {
3333    case Qualifiers::OCL_None:
3334    case Qualifiers::OCL_ExplicitNone:
3335      break;
3336    case Qualifiers::OCL_Strong: name = "__strong"; break;
3337    case Qualifiers::OCL_Weak: name = "__weak"; break;
3338    case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
3339    }
3340    S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
3341      << name << type;
3342  }
3343
3344  Qualifiers qs;
3345  qs.setObjCLifetime(lifetime);
3346  QualType origType = type;
3347  if (!NonObjCPointer)
3348    type = S.Context.getQualifiedType(type, qs);
3349
3350  // If we have a valid source location for the attribute, use an
3351  // AttributedType instead.
3352  if (AttrLoc.isValid())
3353    type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
3354                                       origType, type);
3355
3356  // Forbid __weak if the runtime doesn't support it.
3357  if (lifetime == Qualifiers::OCL_Weak &&
3358      !S.getLangOptions().ObjCRuntimeHasWeak && !NonObjCPointer) {
3359
3360    // Actually, delay this until we know what we're parsing.
3361    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3362      S.DelayedDiagnostics.add(
3363          sema::DelayedDiagnostic::makeForbiddenType(
3364              S.getSourceManager().getExpansionLoc(AttrLoc),
3365              diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3366    } else {
3367      S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
3368    }
3369
3370    attr.setInvalid();
3371    return true;
3372  }
3373
3374  // Forbid __weak for class objects marked as
3375  // objc_arc_weak_reference_unavailable
3376  if (lifetime == Qualifiers::OCL_Weak) {
3377    QualType T = type;
3378    while (const PointerType *ptr = T->getAs<PointerType>())
3379      T = ptr->getPointeeType();
3380    if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
3381      ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
3382      if (Class->isArcWeakrefUnavailable()) {
3383          S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
3384          S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3385                 diag::note_class_declared);
3386      }
3387    }
3388  }
3389
3390  return true;
3391}
3392
3393/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3394/// attribute on the specified type.  Returns true to indicate that
3395/// the attribute was handled, false to indicate that the type does
3396/// not permit the attribute.
3397static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3398                                 AttributeList &attr,
3399                                 QualType &type) {
3400  Sema &S = state.getSema();
3401
3402  // Delay if this isn't some kind of pointer.
3403  if (!type->isPointerType() &&
3404      !type->isObjCObjectPointerType() &&
3405      !type->isBlockPointerType())
3406    return false;
3407
3408  if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3409    S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3410    attr.setInvalid();
3411    return true;
3412  }
3413
3414  // Check the attribute arguments.
3415  if (!attr.getParameterName()) {
3416    S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
3417      << "objc_gc" << 1;
3418    attr.setInvalid();
3419    return true;
3420  }
3421  Qualifiers::GC GCAttr;
3422  if (attr.getNumArgs() != 0) {
3423    S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3424    attr.setInvalid();
3425    return true;
3426  }
3427  if (attr.getParameterName()->isStr("weak"))
3428    GCAttr = Qualifiers::Weak;
3429  else if (attr.getParameterName()->isStr("strong"))
3430    GCAttr = Qualifiers::Strong;
3431  else {
3432    S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3433      << "objc_gc" << attr.getParameterName();
3434    attr.setInvalid();
3435    return true;
3436  }
3437
3438  QualType origType = type;
3439  type = S.Context.getObjCGCQualType(origType, GCAttr);
3440
3441  // Make an attributed type to preserve the source information.
3442  if (attr.getLoc().isValid())
3443    type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3444                                       origType, type);
3445
3446  return true;
3447}
3448
3449namespace {
3450  /// A helper class to unwrap a type down to a function for the
3451  /// purposes of applying attributes there.
3452  ///
3453  /// Use:
3454  ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
3455  ///   if (unwrapped.isFunctionType()) {
3456  ///     const FunctionType *fn = unwrapped.get();
3457  ///     // change fn somehow
3458  ///     T = unwrapped.wrap(fn);
3459  ///   }
3460  struct FunctionTypeUnwrapper {
3461    enum WrapKind {
3462      Desugar,
3463      Parens,
3464      Pointer,
3465      BlockPointer,
3466      Reference,
3467      MemberPointer
3468    };
3469
3470    QualType Original;
3471    const FunctionType *Fn;
3472    SmallVector<unsigned char /*WrapKind*/, 8> Stack;
3473
3474    FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3475      while (true) {
3476        const Type *Ty = T.getTypePtr();
3477        if (isa<FunctionType>(Ty)) {
3478          Fn = cast<FunctionType>(Ty);
3479          return;
3480        } else if (isa<ParenType>(Ty)) {
3481          T = cast<ParenType>(Ty)->getInnerType();
3482          Stack.push_back(Parens);
3483        } else if (isa<PointerType>(Ty)) {
3484          T = cast<PointerType>(Ty)->getPointeeType();
3485          Stack.push_back(Pointer);
3486        } else if (isa<BlockPointerType>(Ty)) {
3487          T = cast<BlockPointerType>(Ty)->getPointeeType();
3488          Stack.push_back(BlockPointer);
3489        } else if (isa<MemberPointerType>(Ty)) {
3490          T = cast<MemberPointerType>(Ty)->getPointeeType();
3491          Stack.push_back(MemberPointer);
3492        } else if (isa<ReferenceType>(Ty)) {
3493          T = cast<ReferenceType>(Ty)->getPointeeType();
3494          Stack.push_back(Reference);
3495        } else {
3496          const Type *DTy = Ty->getUnqualifiedDesugaredType();
3497          if (Ty == DTy) {
3498            Fn = 0;
3499            return;
3500          }
3501
3502          T = QualType(DTy, 0);
3503          Stack.push_back(Desugar);
3504        }
3505      }
3506    }
3507
3508    bool isFunctionType() const { return (Fn != 0); }
3509    const FunctionType *get() const { return Fn; }
3510
3511    QualType wrap(Sema &S, const FunctionType *New) {
3512      // If T wasn't modified from the unwrapped type, do nothing.
3513      if (New == get()) return Original;
3514
3515      Fn = New;
3516      return wrap(S.Context, Original, 0);
3517    }
3518
3519  private:
3520    QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3521      if (I == Stack.size())
3522        return C.getQualifiedType(Fn, Old.getQualifiers());
3523
3524      // Build up the inner type, applying the qualifiers from the old
3525      // type to the new type.
3526      SplitQualType SplitOld = Old.split();
3527
3528      // As a special case, tail-recurse if there are no qualifiers.
3529      if (SplitOld.second.empty())
3530        return wrap(C, SplitOld.first, I);
3531      return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
3532    }
3533
3534    QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3535      if (I == Stack.size()) return QualType(Fn, 0);
3536
3537      switch (static_cast<WrapKind>(Stack[I++])) {
3538      case Desugar:
3539        // This is the point at which we potentially lose source
3540        // information.
3541        return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3542
3543      case Parens: {
3544        QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3545        return C.getParenType(New);
3546      }
3547
3548      case Pointer: {
3549        QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3550        return C.getPointerType(New);
3551      }
3552
3553      case BlockPointer: {
3554        QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3555        return C.getBlockPointerType(New);
3556      }
3557
3558      case MemberPointer: {
3559        const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3560        QualType New = wrap(C, OldMPT->getPointeeType(), I);
3561        return C.getMemberPointerType(New, OldMPT->getClass());
3562      }
3563
3564      case Reference: {
3565        const ReferenceType *OldRef = cast<ReferenceType>(Old);
3566        QualType New = wrap(C, OldRef->getPointeeType(), I);
3567        if (isa<LValueReferenceType>(OldRef))
3568          return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3569        else
3570          return C.getRValueReferenceType(New);
3571      }
3572      }
3573
3574      llvm_unreachable("unknown wrapping kind");
3575      return QualType();
3576    }
3577  };
3578}
3579
3580/// Process an individual function attribute.  Returns true to
3581/// indicate that the attribute was handled, false if it wasn't.
3582static bool handleFunctionTypeAttr(TypeProcessingState &state,
3583                                   AttributeList &attr,
3584                                   QualType &type) {
3585  Sema &S = state.getSema();
3586
3587  FunctionTypeUnwrapper unwrapped(S, type);
3588
3589  if (attr.getKind() == AttributeList::AT_noreturn) {
3590    if (S.CheckNoReturnAttr(attr))
3591      return true;
3592
3593    // Delay if this is not a function type.
3594    if (!unwrapped.isFunctionType())
3595      return false;
3596
3597    // Otherwise we can process right away.
3598    FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3599    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3600    return true;
3601  }
3602
3603  // ns_returns_retained is not always a type attribute, but if we got
3604  // here, we're treating it as one right now.
3605  if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
3606    assert(S.getLangOptions().ObjCAutoRefCount &&
3607           "ns_returns_retained treated as type attribute in non-ARC");
3608    if (attr.getNumArgs()) return true;
3609
3610    // Delay if this is not a function type.
3611    if (!unwrapped.isFunctionType())
3612      return false;
3613
3614    FunctionType::ExtInfo EI
3615      = unwrapped.get()->getExtInfo().withProducesResult(true);
3616    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3617    return true;
3618  }
3619
3620  if (attr.getKind() == AttributeList::AT_regparm) {
3621    unsigned value;
3622    if (S.CheckRegparmAttr(attr, value))
3623      return true;
3624
3625    // Delay if this is not a function type.
3626    if (!unwrapped.isFunctionType())
3627      return false;
3628
3629    // Diagnose regparm with fastcall.
3630    const FunctionType *fn = unwrapped.get();
3631    CallingConv CC = fn->getCallConv();
3632    if (CC == CC_X86FastCall) {
3633      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3634        << FunctionType::getNameForCallConv(CC)
3635        << "regparm";
3636      attr.setInvalid();
3637      return true;
3638    }
3639
3640    FunctionType::ExtInfo EI =
3641      unwrapped.get()->getExtInfo().withRegParm(value);
3642    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3643    return true;
3644  }
3645
3646  // Otherwise, a calling convention.
3647  CallingConv CC;
3648  if (S.CheckCallingConvAttr(attr, CC))
3649    return true;
3650
3651  // Delay if the type didn't work out to a function.
3652  if (!unwrapped.isFunctionType()) return false;
3653
3654  const FunctionType *fn = unwrapped.get();
3655  CallingConv CCOld = fn->getCallConv();
3656  if (S.Context.getCanonicalCallConv(CC) ==
3657      S.Context.getCanonicalCallConv(CCOld)) {
3658    FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3659    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3660    return true;
3661  }
3662
3663  if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
3664    // Should we diagnose reapplications of the same convention?
3665    S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3666      << FunctionType::getNameForCallConv(CC)
3667      << FunctionType::getNameForCallConv(CCOld);
3668    attr.setInvalid();
3669    return true;
3670  }
3671
3672  // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3673  if (CC == CC_X86FastCall) {
3674    if (isa<FunctionNoProtoType>(fn)) {
3675      S.Diag(attr.getLoc(), diag::err_cconv_knr)
3676        << FunctionType::getNameForCallConv(CC);
3677      attr.setInvalid();
3678      return true;
3679    }
3680
3681    const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
3682    if (FnP->isVariadic()) {
3683      S.Diag(attr.getLoc(), diag::err_cconv_varargs)
3684        << FunctionType::getNameForCallConv(CC);
3685      attr.setInvalid();
3686      return true;
3687    }
3688
3689    // Also diagnose fastcall with regparm.
3690    if (fn->getHasRegParm()) {
3691      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3692        << "regparm"
3693        << FunctionType::getNameForCallConv(CC);
3694      attr.setInvalid();
3695      return true;
3696    }
3697  }
3698
3699  FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3700  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3701  return true;
3702}
3703
3704/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3705static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3706                                             const AttributeList &Attr,
3707                                             Sema &S) {
3708  // Check the attribute arguments.
3709  if (Attr.getNumArgs() != 1) {
3710    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3711    Attr.setInvalid();
3712    return;
3713  }
3714  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3715  llvm::APSInt arg(32);
3716  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3717      !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3718    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3719      << "opencl_image_access" << sizeExpr->getSourceRange();
3720    Attr.setInvalid();
3721    return;
3722  }
3723  unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3724  switch (iarg) {
3725  case CLIA_read_only:
3726  case CLIA_write_only:
3727  case CLIA_read_write:
3728    // Implemented in a separate patch
3729    break;
3730  default:
3731    // Implemented in a separate patch
3732    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3733      << sizeExpr->getSourceRange();
3734    Attr.setInvalid();
3735    break;
3736  }
3737}
3738
3739/// HandleVectorSizeAttribute - this attribute is only applicable to integral
3740/// and float scalars, although arrays, pointers, and function return values are
3741/// allowed in conjunction with this construct. Aggregates with this attribute
3742/// are invalid, even if they are of the same size as a corresponding scalar.
3743/// The raw attribute should contain precisely 1 argument, the vector size for
3744/// the variable, measured in bytes. If curType and rawAttr are well formed,
3745/// this routine will return a new vector type.
3746static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3747                                 Sema &S) {
3748  // Check the attribute arguments.
3749  if (Attr.getNumArgs() != 1) {
3750    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3751    Attr.setInvalid();
3752    return;
3753  }
3754  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3755  llvm::APSInt vecSize(32);
3756  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3757      !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
3758    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3759      << "vector_size" << sizeExpr->getSourceRange();
3760    Attr.setInvalid();
3761    return;
3762  }
3763  // the base type must be integer or float, and can't already be a vector.
3764  if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
3765    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
3766    Attr.setInvalid();
3767    return;
3768  }
3769  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3770  // vecSize is specified in bytes - convert to bits.
3771  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3772
3773  // the vector size needs to be an integral multiple of the type size.
3774  if (vectorSize % typeSize) {
3775    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3776      << sizeExpr->getSourceRange();
3777    Attr.setInvalid();
3778    return;
3779  }
3780  if (vectorSize == 0) {
3781    S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3782      << sizeExpr->getSourceRange();
3783    Attr.setInvalid();
3784    return;
3785  }
3786
3787  // Success! Instantiate the vector type, the number of elements is > 0, and
3788  // not required to be a power of 2, unlike GCC.
3789  CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
3790                                    VectorType::GenericVector);
3791}
3792
3793/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
3794/// a type.
3795static void HandleExtVectorTypeAttr(QualType &CurType,
3796                                    const AttributeList &Attr,
3797                                    Sema &S) {
3798  Expr *sizeExpr;
3799
3800  // Special case where the argument is a template id.
3801  if (Attr.getParameterName()) {
3802    CXXScopeSpec SS;
3803    UnqualifiedId id;
3804    id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
3805
3806    ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, id, false,
3807                                          false);
3808    if (Size.isInvalid())
3809      return;
3810
3811    sizeExpr = Size.get();
3812  } else {
3813    // check the attribute arguments.
3814    if (Attr.getNumArgs() != 1) {
3815      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3816      return;
3817    }
3818    sizeExpr = Attr.getArg(0);
3819  }
3820
3821  // Create the vector type.
3822  QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
3823  if (!T.isNull())
3824    CurType = T;
3825}
3826
3827/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3828/// "neon_polyvector_type" attributes are used to create vector types that
3829/// are mangled according to ARM's ABI.  Otherwise, these types are identical
3830/// to those created with the "vector_size" attribute.  Unlike "vector_size"
3831/// the argument to these Neon attributes is the number of vector elements,
3832/// not the vector size in bytes.  The vector width and element type must
3833/// match one of the standard Neon vector types.
3834static void HandleNeonVectorTypeAttr(QualType& CurType,
3835                                     const AttributeList &Attr, Sema &S,
3836                                     VectorType::VectorKind VecKind,
3837                                     const char *AttrName) {
3838  // Check the attribute arguments.
3839  if (Attr.getNumArgs() != 1) {
3840    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3841    Attr.setInvalid();
3842    return;
3843  }
3844  // The number of elements must be an ICE.
3845  Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3846  llvm::APSInt numEltsInt(32);
3847  if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3848      !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3849    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3850      << AttrName << numEltsExpr->getSourceRange();
3851    Attr.setInvalid();
3852    return;
3853  }
3854  // Only certain element types are supported for Neon vectors.
3855  const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3856  if (!BTy ||
3857      (VecKind == VectorType::NeonPolyVector &&
3858       BTy->getKind() != BuiltinType::SChar &&
3859       BTy->getKind() != BuiltinType::Short) ||
3860      (BTy->getKind() != BuiltinType::SChar &&
3861       BTy->getKind() != BuiltinType::UChar &&
3862       BTy->getKind() != BuiltinType::Short &&
3863       BTy->getKind() != BuiltinType::UShort &&
3864       BTy->getKind() != BuiltinType::Int &&
3865       BTy->getKind() != BuiltinType::UInt &&
3866       BTy->getKind() != BuiltinType::LongLong &&
3867       BTy->getKind() != BuiltinType::ULongLong &&
3868       BTy->getKind() != BuiltinType::Float)) {
3869    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3870    Attr.setInvalid();
3871    return;
3872  }
3873  // The total size of the vector must be 64 or 128 bits.
3874  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3875  unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3876  unsigned vecSize = typeSize * numElts;
3877  if (vecSize != 64 && vecSize != 128) {
3878    S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3879    Attr.setInvalid();
3880    return;
3881  }
3882
3883  CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3884}
3885
3886static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3887                             bool isDeclSpec, AttributeList *attrs) {
3888  // Scan through and apply attributes to this type where it makes sense.  Some
3889  // attributes (such as __address_space__, __vector_size__, etc) apply to the
3890  // type, but others can be present in the type specifiers even though they
3891  // apply to the decl.  Here we apply type attributes and ignore the rest.
3892
3893  AttributeList *next;
3894  do {
3895    AttributeList &attr = *attrs;
3896    next = attr.getNext();
3897
3898    // Skip attributes that were marked to be invalid.
3899    if (attr.isInvalid())
3900      continue;
3901
3902    // If this is an attribute we can handle, do so now,
3903    // otherwise, add it to the FnAttrs list for rechaining.
3904    switch (attr.getKind()) {
3905    default: break;
3906
3907    case AttributeList::AT_may_alias:
3908      // FIXME: This attribute needs to actually be handled, but if we ignore
3909      // it it breaks large amounts of Linux software.
3910      attr.setUsedAsTypeAttr();
3911      break;
3912    case AttributeList::AT_address_space:
3913      HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
3914      attr.setUsedAsTypeAttr();
3915      break;
3916    OBJC_POINTER_TYPE_ATTRS_CASELIST:
3917      if (!handleObjCPointerTypeAttr(state, attr, type))
3918        distributeObjCPointerTypeAttr(state, attr, type);
3919      attr.setUsedAsTypeAttr();
3920      break;
3921    case AttributeList::AT_vector_size:
3922      HandleVectorSizeAttr(type, attr, state.getSema());
3923      attr.setUsedAsTypeAttr();
3924      break;
3925    case AttributeList::AT_ext_vector_type:
3926      if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
3927            != DeclSpec::SCS_typedef)
3928        HandleExtVectorTypeAttr(type, attr, state.getSema());
3929      attr.setUsedAsTypeAttr();
3930      break;
3931    case AttributeList::AT_neon_vector_type:
3932      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3933                               VectorType::NeonVector, "neon_vector_type");
3934      attr.setUsedAsTypeAttr();
3935      break;
3936    case AttributeList::AT_neon_polyvector_type:
3937      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3938                               VectorType::NeonPolyVector,
3939                               "neon_polyvector_type");
3940      attr.setUsedAsTypeAttr();
3941      break;
3942    case AttributeList::AT_opencl_image_access:
3943      HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
3944      attr.setUsedAsTypeAttr();
3945      break;
3946
3947    case AttributeList::AT_ns_returns_retained:
3948      if (!state.getSema().getLangOptions().ObjCAutoRefCount)
3949	break;
3950      // fallthrough into the function attrs
3951
3952    FUNCTION_TYPE_ATTRS_CASELIST:
3953      attr.setUsedAsTypeAttr();
3954
3955      // Never process function type attributes as part of the
3956      // declaration-specifiers.
3957      if (isDeclSpec)
3958        distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3959
3960      // Otherwise, handle the possible delays.
3961      else if (!handleFunctionTypeAttr(state, attr, type))
3962        distributeFunctionTypeAttr(state, attr, type);
3963      break;
3964    }
3965  } while ((attrs = next));
3966}
3967
3968/// \brief Ensure that the type of the given expression is complete.
3969///
3970/// This routine checks whether the expression \p E has a complete type. If the
3971/// expression refers to an instantiable construct, that instantiation is
3972/// performed as needed to complete its type. Furthermore
3973/// Sema::RequireCompleteType is called for the expression's type (or in the
3974/// case of a reference type, the referred-to type).
3975///
3976/// \param E The expression whose type is required to be complete.
3977/// \param PD The partial diagnostic that will be printed out if the type cannot
3978/// be completed.
3979///
3980/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
3981/// otherwise.
3982bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
3983                                   std::pair<SourceLocation,
3984                                             PartialDiagnostic> Note) {
3985  QualType T = E->getType();
3986
3987  // Fast path the case where the type is already complete.
3988  if (!T->isIncompleteType())
3989    return false;
3990
3991  // Incomplete array types may be completed by the initializer attached to
3992  // their definitions. For static data members of class templates we need to
3993  // instantiate the definition to get this initializer and complete the type.
3994  if (T->isIncompleteArrayType()) {
3995    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3996      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3997        if (Var->isStaticDataMember() &&
3998            Var->getInstantiatedFromStaticDataMember()) {
3999
4000          MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4001          assert(MSInfo && "Missing member specialization information?");
4002          if (MSInfo->getTemplateSpecializationKind()
4003                != TSK_ExplicitSpecialization) {
4004            // If we don't already have a point of instantiation, this is it.
4005            if (MSInfo->getPointOfInstantiation().isInvalid()) {
4006              MSInfo->setPointOfInstantiation(E->getLocStart());
4007
4008              // This is a modification of an existing AST node. Notify
4009              // listeners.
4010              if (ASTMutationListener *L = getASTMutationListener())
4011                L->StaticDataMemberInstantiated(Var);
4012            }
4013
4014            InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
4015
4016            // Update the type to the newly instantiated definition's type both
4017            // here and within the expression.
4018            if (VarDecl *Def = Var->getDefinition()) {
4019              DRE->setDecl(Def);
4020              T = Def->getType();
4021              DRE->setType(T);
4022              E->setType(T);
4023            }
4024          }
4025
4026          // We still go on to try to complete the type independently, as it
4027          // may also require instantiations or diagnostics if it remains
4028          // incomplete.
4029        }
4030      }
4031    }
4032  }
4033
4034  // FIXME: Are there other cases which require instantiating something other
4035  // than the type to complete the type of an expression?
4036
4037  // Look through reference types and complete the referred type.
4038  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4039    T = Ref->getPointeeType();
4040
4041  return RequireCompleteType(E->getExprLoc(), T, PD, Note);
4042}
4043
4044/// @brief Ensure that the type T is a complete type.
4045///
4046/// This routine checks whether the type @p T is complete in any
4047/// context where a complete type is required. If @p T is a complete
4048/// type, returns false. If @p T is a class template specialization,
4049/// this routine then attempts to perform class template
4050/// instantiation. If instantiation fails, or if @p T is incomplete
4051/// and cannot be completed, issues the diagnostic @p diag (giving it
4052/// the type @p T) and returns true.
4053///
4054/// @param Loc  The location in the source that the incomplete type
4055/// diagnostic should refer to.
4056///
4057/// @param T  The type that this routine is examining for completeness.
4058///
4059/// @param PD The partial diagnostic that will be printed out if T is not a
4060/// complete type.
4061///
4062/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4063/// @c false otherwise.
4064bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4065                               const PartialDiagnostic &PD,
4066                               std::pair<SourceLocation,
4067                                         PartialDiagnostic> Note) {
4068  unsigned diag = PD.getDiagID();
4069
4070  // FIXME: Add this assertion to make sure we always get instantiation points.
4071  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
4072  // FIXME: Add this assertion to help us flush out problems with
4073  // checking for dependent types and type-dependent expressions.
4074  //
4075  //  assert(!T->isDependentType() &&
4076  //         "Can't ask whether a dependent type is complete");
4077
4078  // If we have a complete type, we're done.
4079  NamedDecl *Def = 0;
4080  if (!T->isIncompleteType(&Def)) {
4081    // If we know about the definition but it is not visible, complain.
4082    if (diag != 0 && Def && !LookupResult::isVisible(Def)) {
4083      // Suppress this error outside of a SFINAE context if we've already
4084      // emitted the error once for this type. There's no usefulness in
4085      // repeating the diagnostic.
4086      // FIXME: Add a Fix-It that imports the corresponding module or includes
4087      // the header.
4088      if (isSFINAEContext() || HiddenDefinitions.insert(Def)) {
4089        Diag(Loc, diag::err_module_private_definition) << T;
4090        Diag(Def->getLocation(), diag::note_previous_definition);
4091      }
4092    }
4093
4094    return false;
4095  }
4096
4097  const TagType *Tag = T->getAs<TagType>();
4098  const ObjCInterfaceType *IFace = 0;
4099
4100  if (Tag) {
4101    // Avoid diagnosing invalid decls as incomplete.
4102    if (Tag->getDecl()->isInvalidDecl())
4103      return true;
4104
4105    // Give the external AST source a chance to complete the type.
4106    if (Tag->getDecl()->hasExternalLexicalStorage()) {
4107      Context.getExternalSource()->CompleteType(Tag->getDecl());
4108      if (!Tag->isIncompleteType())
4109        return false;
4110    }
4111  }
4112  else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4113    // Avoid diagnosing invalid decls as incomplete.
4114    if (IFace->getDecl()->isInvalidDecl())
4115      return true;
4116
4117    // Give the external AST source a chance to complete the type.
4118    if (IFace->getDecl()->hasExternalLexicalStorage()) {
4119      Context.getExternalSource()->CompleteType(IFace->getDecl());
4120      if (!IFace->isIncompleteType())
4121        return false;
4122    }
4123  }
4124
4125  // If we have a class template specialization or a class member of a
4126  // class template specialization, or an array with known size of such,
4127  // try to instantiate it.
4128  QualType MaybeTemplate = T;
4129  if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
4130    MaybeTemplate = Array->getElementType();
4131  if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
4132    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
4133          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
4134      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4135        return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
4136                                                      TSK_ImplicitInstantiation,
4137                                                      /*Complain=*/diag != 0);
4138    } else if (CXXRecordDecl *Rec
4139                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
4140      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
4141        MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
4142        assert(MSInfo && "Missing member specialization information?");
4143        // This record was instantiated from a class within a template.
4144        if (MSInfo->getTemplateSpecializationKind()
4145                                               != TSK_ExplicitSpecialization)
4146          return InstantiateClass(Loc, Rec, Pattern,
4147                                  getTemplateInstantiationArgs(Rec),
4148                                  TSK_ImplicitInstantiation,
4149                                  /*Complain=*/diag != 0);
4150      }
4151    }
4152  }
4153
4154  if (diag == 0)
4155    return true;
4156
4157  // We have an incomplete type. Produce a diagnostic.
4158  Diag(Loc, PD) << T;
4159
4160  // If we have a note, produce it.
4161  if (!Note.first.isInvalid())
4162    Diag(Note.first, Note.second);
4163
4164  // If the type was a forward declaration of a class/struct/union
4165  // type, produce a note.
4166  if (Tag && !Tag->getDecl()->isInvalidDecl())
4167    Diag(Tag->getDecl()->getLocation(),
4168         Tag->isBeingDefined() ? diag::note_type_being_defined
4169                               : diag::note_forward_declaration)
4170      << QualType(Tag, 0);
4171
4172  // If the Objective-C class was a forward declaration, produce a note.
4173  if (IFace && !IFace->getDecl()->isInvalidDecl())
4174    Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
4175
4176  return true;
4177}
4178
4179bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4180                               const PartialDiagnostic &PD) {
4181  return RequireCompleteType(Loc, T, PD,
4182                             std::make_pair(SourceLocation(), PDiag(0)));
4183}
4184
4185bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4186                               unsigned DiagID) {
4187  return RequireCompleteType(Loc, T, PDiag(DiagID),
4188                             std::make_pair(SourceLocation(), PDiag(0)));
4189}
4190
4191/// @brief Ensure that the type T is a literal type.
4192///
4193/// This routine checks whether the type @p T is a literal type. If @p T is an
4194/// incomplete type, an attempt is made to complete it. If @p T is a literal
4195/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4196/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4197/// it the type @p T), along with notes explaining why the type is not a
4198/// literal type, and returns true.
4199///
4200/// @param Loc  The location in the source that the non-literal type
4201/// diagnostic should refer to.
4202///
4203/// @param T  The type that this routine is examining for literalness.
4204///
4205/// @param PD The partial diagnostic that will be printed out if T is not a
4206/// literal type.
4207///
4208/// @param AllowIncompleteType If true, an incomplete type will be considered
4209/// acceptable.
4210///
4211/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4212/// @c false otherwise.
4213bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
4214                              const PartialDiagnostic &PD,
4215                              bool AllowIncompleteType) {
4216  assert(!T->isDependentType() && "type should not be dependent");
4217
4218  bool Incomplete = RequireCompleteType(Loc, T, 0);
4219  if (T->isLiteralType() || (AllowIncompleteType && Incomplete))
4220    return false;
4221
4222  if (PD.getDiagID() == 0)
4223    return true;
4224
4225  Diag(Loc, PD) << T;
4226
4227  if (T->isVariableArrayType())
4228    return true;
4229
4230  const RecordType *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>();
4231  if (!RT)
4232    return true;
4233
4234  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4235
4236  // If the class has virtual base classes, then it's not an aggregate, and
4237  // cannot have any constexpr constructors, so is non-literal. This is better
4238  // to diagnose than the resulting absence of constexpr constructors.
4239  if (RD->getNumVBases()) {
4240    Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
4241      << RD->isStruct() << RD->getNumVBases();
4242    for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4243           E = RD->vbases_end(); I != E; ++I)
4244      Diag(I->getSourceRange().getBegin(),
4245           diag::note_constexpr_virtual_base_here) << I->getSourceRange();
4246  } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor()) {
4247    Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
4248
4249    switch (RD->getTemplateSpecializationKind()) {
4250    case TSK_Undeclared:
4251    case TSK_ExplicitSpecialization:
4252      break;
4253
4254    case TSK_ImplicitInstantiation:
4255    case TSK_ExplicitInstantiationDeclaration:
4256    case TSK_ExplicitInstantiationDefinition:
4257      // If the base template had constexpr constructors which were
4258      // instantiated as non-constexpr constructors, explain why.
4259      for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4260           E = RD->ctor_end(); I != E; ++I) {
4261        if ((*I)->isCopyConstructor() || (*I)->isMoveConstructor())
4262          continue;
4263
4264        FunctionDecl *Base = (*I)->getInstantiatedFromMemberFunction();
4265        if (Base && Base->isConstexpr())
4266          CheckConstexprFunctionDecl(*I, CCK_NoteNonConstexprInstantiation);
4267      }
4268    }
4269  } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4270    for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4271         E = RD->bases_end(); I != E; ++I) {
4272      if (!I->getType()->isLiteralType()) {
4273        Diag(I->getSourceRange().getBegin(),
4274             diag::note_non_literal_base_class)
4275          << RD << I->getType() << I->getSourceRange();
4276        return true;
4277      }
4278    }
4279    for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4280         E = RD->field_end(); I != E; ++I) {
4281      if (!(*I)->getType()->isLiteralType()) {
4282        Diag((*I)->getLocation(), diag::note_non_literal_field)
4283          << RD << (*I) << (*I)->getType();
4284        return true;
4285      } else if ((*I)->isMutable()) {
4286        Diag((*I)->getLocation(), diag::note_non_literal_mutable_field) << RD;
4287        return true;
4288      }
4289    }
4290  } else if (!RD->hasTrivialDestructor()) {
4291    // All fields and bases are of literal types, so have trivial destructors.
4292    // If this class's destructor is non-trivial it must be user-declared.
4293    CXXDestructorDecl *Dtor = RD->getDestructor();
4294    assert(Dtor && "class has literal fields and bases but no dtor?");
4295    if (!Dtor)
4296      return true;
4297
4298    Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4299         diag::note_non_literal_user_provided_dtor :
4300         diag::note_non_literal_nontrivial_dtor) << RD;
4301  }
4302
4303  return true;
4304}
4305
4306/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4307/// and qualified by the nested-name-specifier contained in SS.
4308QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4309                                 const CXXScopeSpec &SS, QualType T) {
4310  if (T.isNull())
4311    return T;
4312  NestedNameSpecifier *NNS;
4313  if (SS.isValid())
4314    NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4315  else {
4316    if (Keyword == ETK_None)
4317      return T;
4318    NNS = 0;
4319  }
4320  return Context.getElaboratedType(Keyword, NNS, T);
4321}
4322
4323QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
4324  ExprResult ER = CheckPlaceholderExpr(E);
4325  if (ER.isInvalid()) return QualType();
4326  E = ER.take();
4327
4328  if (!E->isTypeDependent()) {
4329    QualType T = E->getType();
4330    if (const TagType *TT = T->getAs<TagType>())
4331      DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
4332  }
4333  return Context.getTypeOfExprType(E);
4334}
4335
4336QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
4337  ExprResult ER = CheckPlaceholderExpr(E);
4338  if (ER.isInvalid()) return QualType();
4339  E = ER.take();
4340
4341  return Context.getDecltypeType(E);
4342}
4343
4344QualType Sema::BuildUnaryTransformType(QualType BaseType,
4345                                       UnaryTransformType::UTTKind UKind,
4346                                       SourceLocation Loc) {
4347  switch (UKind) {
4348  case UnaryTransformType::EnumUnderlyingType:
4349    if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4350      Diag(Loc, diag::err_only_enums_have_underlying_types);
4351      return QualType();
4352    } else {
4353      QualType Underlying = BaseType;
4354      if (!BaseType->isDependentType()) {
4355        EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4356        assert(ED && "EnumType has no EnumDecl");
4357        DiagnoseUseOfDecl(ED, Loc);
4358        Underlying = ED->getIntegerType();
4359      }
4360      assert(!Underlying.isNull());
4361      return Context.getUnaryTransformType(BaseType, Underlying,
4362                                        UnaryTransformType::EnumUnderlyingType);
4363    }
4364  }
4365  llvm_unreachable("unknown unary transform type");
4366}
4367
4368QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
4369  if (!T->isDependentType()) {
4370    int DisallowedKind = -1;
4371    if (T->isIncompleteType())
4372      // FIXME: It isn't entirely clear whether incomplete atomic types
4373      // are allowed or not; for simplicity, ban them for the moment.
4374      DisallowedKind = 0;
4375    else if (T->isArrayType())
4376      DisallowedKind = 1;
4377    else if (T->isFunctionType())
4378      DisallowedKind = 2;
4379    else if (T->isReferenceType())
4380      DisallowedKind = 3;
4381    else if (T->isAtomicType())
4382      DisallowedKind = 4;
4383    else if (T.hasQualifiers())
4384      DisallowedKind = 5;
4385    else if (!T.isTriviallyCopyableType(Context))
4386      // Some other non-trivially-copyable type (probably a C++ class)
4387      DisallowedKind = 6;
4388
4389    if (DisallowedKind != -1) {
4390      Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
4391      return QualType();
4392    }
4393
4394    // FIXME: Do we need any handling for ARC here?
4395  }
4396
4397  // Build the pointer type.
4398  return Context.getAtomicType(T);
4399}
4400