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