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