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