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