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