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