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