ASTContext.cpp revision 14108da7f7fc059772711e4ffee1322a27b152a7
1//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
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 the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExternalASTSource.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/Basic/Builtins.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/MathExtras.h"
26#include "llvm/Support/MemoryBuffer.h"
27using namespace clang;
28
29enum FloatingRank {
30  FloatRank, DoubleRank, LongDoubleRank
31};
32
33ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
34                       TargetInfo &t,
35                       IdentifierTable &idents, SelectorTable &sels,
36                       Builtin::Context &builtins,
37                       bool FreeMem, unsigned size_reserve) :
38  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
39  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
40  SourceMgr(SM), LangOpts(LOpts),
41  LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
42  Idents(idents), Selectors(sels),
43  BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
44  if (size_reserve > 0) Types.reserve(size_reserve);
45  TUDecl = TranslationUnitDecl::Create(*this);
46  InitBuiltinTypes();
47}
48
49ASTContext::~ASTContext() {
50  // Deallocate all the types.
51  while (!Types.empty()) {
52    Types.back()->Destroy(*this);
53    Types.pop_back();
54  }
55
56  {
57    llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
58      I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
59    while (I != E) {
60      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
61      delete R;
62    }
63  }
64
65  {
66    llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
67      I = ObjCLayouts.begin(), E = ObjCLayouts.end();
68    while (I != E) {
69      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
70      delete R;
71    }
72  }
73
74  // Destroy nested-name-specifiers.
75  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
76         NNS = NestedNameSpecifiers.begin(),
77         NNSEnd = NestedNameSpecifiers.end();
78       NNS != NNSEnd;
79       /* Increment in loop */)
80    (*NNS++).Destroy(*this);
81
82  if (GlobalNestedNameSpecifier)
83    GlobalNestedNameSpecifier->Destroy(*this);
84
85  TUDecl->Destroy(*this);
86}
87
88void
89ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
90  ExternalSource.reset(Source.take());
91}
92
93void ASTContext::PrintStats() const {
94  fprintf(stderr, "*** AST Context Stats:\n");
95  fprintf(stderr, "  %d types total.\n", (int)Types.size());
96
97  unsigned counts[] = {
98#define TYPE(Name, Parent) 0,
99#define ABSTRACT_TYPE(Name, Parent)
100#include "clang/AST/TypeNodes.def"
101    0 // Extra
102  };
103
104  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
105    Type *T = Types[i];
106    counts[(unsigned)T->getTypeClass()]++;
107  }
108
109  unsigned Idx = 0;
110  unsigned TotalBytes = 0;
111#define TYPE(Name, Parent)                                              \
112  if (counts[Idx])                                                      \
113    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
114  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
115  ++Idx;
116#define ABSTRACT_TYPE(Name, Parent)
117#include "clang/AST/TypeNodes.def"
118
119  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
120
121  if (ExternalSource.get()) {
122    fprintf(stderr, "\n");
123    ExternalSource->PrintStats();
124  }
125}
126
127
128void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
129  Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
130}
131
132void ASTContext::InitBuiltinTypes() {
133  assert(VoidTy.isNull() && "Context reinitialized?");
134
135  // C99 6.2.5p19.
136  InitBuiltinType(VoidTy,              BuiltinType::Void);
137
138  // C99 6.2.5p2.
139  InitBuiltinType(BoolTy,              BuiltinType::Bool);
140  // C99 6.2.5p3.
141  if (LangOpts.CharIsSigned)
142    InitBuiltinType(CharTy,            BuiltinType::Char_S);
143  else
144    InitBuiltinType(CharTy,            BuiltinType::Char_U);
145  // C99 6.2.5p4.
146  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
147  InitBuiltinType(ShortTy,             BuiltinType::Short);
148  InitBuiltinType(IntTy,               BuiltinType::Int);
149  InitBuiltinType(LongTy,              BuiltinType::Long);
150  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
151
152  // C99 6.2.5p6.
153  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
154  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
155  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
156  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
157  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
158
159  // C99 6.2.5p10.
160  InitBuiltinType(FloatTy,             BuiltinType::Float);
161  InitBuiltinType(DoubleTy,            BuiltinType::Double);
162  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
163
164  // GNU extension, 128-bit integers.
165  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
166  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
167
168  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
169    InitBuiltinType(WCharTy,           BuiltinType::WChar);
170  else // C99
171    WCharTy = getFromTargetType(Target.getWCharType());
172
173  // Placeholder type for functions.
174  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
175
176  // Placeholder type for type-dependent expressions whose type is
177  // completely unknown. No code should ever check a type against
178  // DependentTy and users should never see it; however, it is here to
179  // help diagnose failures to properly check for type-dependent
180  // expressions.
181  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
182
183  // Placeholder type for C++0x auto declarations whose real type has
184  // not yet been deduced.
185  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
186
187  // C99 6.2.5p11.
188  FloatComplexTy      = getComplexType(FloatTy);
189  DoubleComplexTy     = getComplexType(DoubleTy);
190  LongDoubleComplexTy = getComplexType(LongDoubleTy);
191
192  BuiltinVaListType = QualType();
193
194  ObjCIdType = QualType();
195  ObjCClassType = QualType();
196
197  ObjCConstantStringType = QualType();
198
199  // void * type
200  VoidPtrTy = getPointerType(VoidTy);
201
202  // nullptr type (C++0x 2.14.7)
203  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
204}
205
206namespace {
207  class BeforeInTranslationUnit
208    : std::binary_function<SourceRange, SourceRange, bool> {
209    SourceManager *SourceMgr;
210
211  public:
212    explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
213
214    bool operator()(SourceRange X, SourceRange Y) {
215      return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
216    }
217  };
218}
219
220/// \brief Determine whether the given comment is a Doxygen-style comment.
221///
222/// \param Start the start of the comment text.
223///
224/// \param End the end of the comment text.
225///
226/// \param Member whether we want to check whether this is a member comment
227/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
228/// we only return true when we find a non-member comment.
229static bool
230isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
231                 bool Member = false) {
232  const char *BufferStart
233    = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
234  const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
235  const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
236
237  if (End - Start < 4)
238    return false;
239
240  assert(Start[0] == '/' && "Not a comment?");
241  if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
242    return false;
243  if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
244    return false;
245
246  return (Start[3] == '<') == Member;
247}
248
249/// \brief Retrieve the comment associated with the given declaration, if
250/// it has one.
251const char *ASTContext::getCommentForDecl(const Decl *D) {
252  if (!D)
253    return 0;
254
255  // Check whether we have cached a comment string for this declaration
256  // already.
257  llvm::DenseMap<const Decl *, std::string>::iterator Pos
258    = DeclComments.find(D);
259  if (Pos != DeclComments.end())
260    return Pos->second.c_str();
261
262  // If we have an external AST source and have not yet loaded comments from
263  // that source, do so now.
264  if (ExternalSource && !LoadedExternalComments) {
265    std::vector<SourceRange> LoadedComments;
266    ExternalSource->ReadComments(LoadedComments);
267
268    if (!LoadedComments.empty())
269      Comments.insert(Comments.begin(), LoadedComments.begin(),
270                      LoadedComments.end());
271
272    LoadedExternalComments = true;
273  }
274
275  // If there are no comments anywhere, we won't find anything.
276  if (Comments.empty())
277    return 0;
278
279  // If the declaration doesn't map directly to a location in a file, we
280  // can't find the comment.
281  SourceLocation DeclStartLoc = D->getLocStart();
282  if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
283    return 0;
284
285  // Find the comment that occurs just before this declaration.
286  std::vector<SourceRange>::iterator LastComment
287    = std::lower_bound(Comments.begin(), Comments.end(),
288                       SourceRange(DeclStartLoc),
289                       BeforeInTranslationUnit(&SourceMgr));
290
291  // Decompose the location for the start of the declaration and find the
292  // beginning of the file buffer.
293  std::pair<FileID, unsigned> DeclStartDecomp
294    = SourceMgr.getDecomposedLoc(DeclStartLoc);
295  const char *FileBufferStart
296    = SourceMgr.getBufferData(DeclStartDecomp.first).first;
297
298  // First check whether we have a comment for a member.
299  if (LastComment != Comments.end() &&
300      !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
301      isDoxygenComment(SourceMgr, *LastComment, true)) {
302    std::pair<FileID, unsigned> LastCommentEndDecomp
303      = SourceMgr.getDecomposedLoc(LastComment->getEnd());
304    if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
305        SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
306          == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
307                                     LastCommentEndDecomp.second)) {
308      // The Doxygen member comment comes after the declaration starts and
309      // is on the same line and in the same file as the declaration. This
310      // is the comment we want.
311      std::string &Result = DeclComments[D];
312      Result.append(FileBufferStart +
313                      SourceMgr.getFileOffset(LastComment->getBegin()),
314                    FileBufferStart + LastCommentEndDecomp.second + 1);
315      return Result.c_str();
316    }
317  }
318
319  if (LastComment == Comments.begin())
320    return 0;
321  --LastComment;
322
323  // Decompose the end of the comment.
324  std::pair<FileID, unsigned> LastCommentEndDecomp
325    = SourceMgr.getDecomposedLoc(LastComment->getEnd());
326
327  // If the comment and the declaration aren't in the same file, then they
328  // aren't related.
329  if (DeclStartDecomp.first != LastCommentEndDecomp.first)
330    return 0;
331
332  // Check that we actually have a Doxygen comment.
333  if (!isDoxygenComment(SourceMgr, *LastComment))
334    return 0;
335
336  // Compute the starting line for the declaration and for the end of the
337  // comment (this is expensive).
338  unsigned DeclStartLine
339    = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
340  unsigned CommentEndLine
341    = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
342                              LastCommentEndDecomp.second);
343
344  // If the comment does not end on the line prior to the declaration, then
345  // the comment is not associated with the declaration at all.
346  if (CommentEndLine + 1 != DeclStartLine)
347    return 0;
348
349  // We have a comment, but there may be more comments on the previous lines.
350  // Keep looking so long as the comments are still Doxygen comments and are
351  // still adjacent.
352  unsigned ExpectedLine
353    = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
354  std::vector<SourceRange>::iterator FirstComment = LastComment;
355  while (FirstComment != Comments.begin()) {
356    // Look at the previous comment
357    --FirstComment;
358    std::pair<FileID, unsigned> Decomp
359      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
360
361    // If this previous comment is in a different file, we're done.
362    if (Decomp.first != DeclStartDecomp.first) {
363      ++FirstComment;
364      break;
365    }
366
367    // If this comment is not a Doxygen comment, we're done.
368    if (!isDoxygenComment(SourceMgr, *FirstComment)) {
369      ++FirstComment;
370      break;
371    }
372
373    // If the line number is not what we expected, we're done.
374    unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
375    if (Line != ExpectedLine) {
376      ++FirstComment;
377      break;
378    }
379
380    // Set the next expected line number.
381    ExpectedLine
382      = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
383  }
384
385  // The iterator range [FirstComment, LastComment] contains all of the
386  // BCPL comments that, together, are associated with this declaration.
387  // Form a single comment block string for this declaration that concatenates
388  // all of these comments.
389  std::string &Result = DeclComments[D];
390  while (FirstComment != LastComment) {
391    std::pair<FileID, unsigned> DecompStart
392      = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
393    std::pair<FileID, unsigned> DecompEnd
394      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
395    Result.append(FileBufferStart + DecompStart.second,
396                  FileBufferStart + DecompEnd.second + 1);
397    ++FirstComment;
398  }
399
400  // Append the last comment line.
401  Result.append(FileBufferStart +
402                  SourceMgr.getFileOffset(LastComment->getBegin()),
403                FileBufferStart + LastCommentEndDecomp.second + 1);
404  return Result.c_str();
405}
406
407//===----------------------------------------------------------------------===//
408//                         Type Sizing and Analysis
409//===----------------------------------------------------------------------===//
410
411/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
412/// scalar floating point type.
413const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
414  const BuiltinType *BT = T->getAsBuiltinType();
415  assert(BT && "Not a floating point type!");
416  switch (BT->getKind()) {
417  default: assert(0 && "Not a floating point type!");
418  case BuiltinType::Float:      return Target.getFloatFormat();
419  case BuiltinType::Double:     return Target.getDoubleFormat();
420  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
421  }
422}
423
424/// getDeclAlign - Return a conservative estimate of the alignment of the
425/// specified decl.  Note that bitfields do not have a valid alignment, so
426/// this method will assert on them.
427unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
428  unsigned Align = Target.getCharWidth();
429
430  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
431    Align = std::max(Align, AA->getAlignment());
432
433  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
434    QualType T = VD->getType();
435    if (const ReferenceType* RT = T->getAsReferenceType()) {
436      unsigned AS = RT->getPointeeType().getAddressSpace();
437      Align = Target.getPointerAlign(AS);
438    } else if (!T->isIncompleteType() && !T->isFunctionType()) {
439      // Incomplete or function types default to 1.
440      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
441        T = cast<ArrayType>(T)->getElementType();
442
443      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
444    }
445  }
446
447  return Align / Target.getCharWidth();
448}
449
450/// getTypeSize - Return the size of the specified type, in bits.  This method
451/// does not work on incomplete types.
452std::pair<uint64_t, unsigned>
453ASTContext::getTypeInfo(const Type *T) {
454  uint64_t Width=0;
455  unsigned Align=8;
456  switch (T->getTypeClass()) {
457#define TYPE(Class, Base)
458#define ABSTRACT_TYPE(Class, Base)
459#define NON_CANONICAL_TYPE(Class, Base)
460#define DEPENDENT_TYPE(Class, Base) case Type::Class:
461#include "clang/AST/TypeNodes.def"
462    assert(false && "Should not see dependent types");
463    break;
464
465  case Type::FunctionNoProto:
466  case Type::FunctionProto:
467    // GCC extension: alignof(function) = 32 bits
468    Width = 0;
469    Align = 32;
470    break;
471
472  case Type::IncompleteArray:
473  case Type::VariableArray:
474    Width = 0;
475    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
476    break;
477
478  case Type::ConstantArrayWithExpr:
479  case Type::ConstantArrayWithoutExpr:
480  case Type::ConstantArray: {
481    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
482
483    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
484    Width = EltInfo.first*CAT->getSize().getZExtValue();
485    Align = EltInfo.second;
486    break;
487  }
488  case Type::ExtVector:
489  case Type::Vector: {
490    std::pair<uint64_t, unsigned> EltInfo =
491      getTypeInfo(cast<VectorType>(T)->getElementType());
492    Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
493    Align = Width;
494    // If the alignment is not a power of 2, round up to the next power of 2.
495    // This happens for non-power-of-2 length vectors.
496    // FIXME: this should probably be a target property.
497    Align = 1 << llvm::Log2_32_Ceil(Align);
498    break;
499  }
500
501  case Type::Builtin:
502    switch (cast<BuiltinType>(T)->getKind()) {
503    default: assert(0 && "Unknown builtin type!");
504    case BuiltinType::Void:
505      // GCC extension: alignof(void) = 8 bits.
506      Width = 0;
507      Align = 8;
508      break;
509
510    case BuiltinType::Bool:
511      Width = Target.getBoolWidth();
512      Align = Target.getBoolAlign();
513      break;
514    case BuiltinType::Char_S:
515    case BuiltinType::Char_U:
516    case BuiltinType::UChar:
517    case BuiltinType::SChar:
518      Width = Target.getCharWidth();
519      Align = Target.getCharAlign();
520      break;
521    case BuiltinType::WChar:
522      Width = Target.getWCharWidth();
523      Align = Target.getWCharAlign();
524      break;
525    case BuiltinType::UShort:
526    case BuiltinType::Short:
527      Width = Target.getShortWidth();
528      Align = Target.getShortAlign();
529      break;
530    case BuiltinType::UInt:
531    case BuiltinType::Int:
532      Width = Target.getIntWidth();
533      Align = Target.getIntAlign();
534      break;
535    case BuiltinType::ULong:
536    case BuiltinType::Long:
537      Width = Target.getLongWidth();
538      Align = Target.getLongAlign();
539      break;
540    case BuiltinType::ULongLong:
541    case BuiltinType::LongLong:
542      Width = Target.getLongLongWidth();
543      Align = Target.getLongLongAlign();
544      break;
545    case BuiltinType::Int128:
546    case BuiltinType::UInt128:
547      Width = 128;
548      Align = 128; // int128_t is 128-bit aligned on all targets.
549      break;
550    case BuiltinType::Float:
551      Width = Target.getFloatWidth();
552      Align = Target.getFloatAlign();
553      break;
554    case BuiltinType::Double:
555      Width = Target.getDoubleWidth();
556      Align = Target.getDoubleAlign();
557      break;
558    case BuiltinType::LongDouble:
559      Width = Target.getLongDoubleWidth();
560      Align = Target.getLongDoubleAlign();
561      break;
562    case BuiltinType::NullPtr:
563      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
564      Align = Target.getPointerAlign(0); //   == sizeof(void*)
565      break;
566    }
567    break;
568  case Type::FixedWidthInt:
569    // FIXME: This isn't precisely correct; the width/alignment should depend
570    // on the available types for the target
571    Width = cast<FixedWidthIntType>(T)->getWidth();
572    Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
573    Align = Width;
574    break;
575  case Type::ExtQual:
576    // FIXME: Pointers into different addr spaces could have different sizes and
577    // alignment requirements: getPointerInfo should take an AddrSpace.
578    return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
579  case Type::ObjCObjectPointer:
580  case Type::ObjCQualifiedInterface:
581    Width = Target.getPointerWidth(0);
582    Align = Target.getPointerAlign(0);
583    break;
584  case Type::BlockPointer: {
585    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
586    Width = Target.getPointerWidth(AS);
587    Align = Target.getPointerAlign(AS);
588    break;
589  }
590  case Type::Pointer: {
591    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
592    Width = Target.getPointerWidth(AS);
593    Align = Target.getPointerAlign(AS);
594    break;
595  }
596  case Type::LValueReference:
597  case Type::RValueReference:
598    // "When applied to a reference or a reference type, the result is the size
599    // of the referenced type." C++98 5.3.3p2: expr.sizeof.
600    // FIXME: This is wrong for struct layout: a reference in a struct has
601    // pointer size.
602    return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
603  case Type::MemberPointer: {
604    // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
605    // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
606    // If we ever want to support other ABIs this needs to be abstracted.
607
608    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
609    std::pair<uint64_t, unsigned> PtrDiffInfo =
610      getTypeInfo(getPointerDiffType());
611    Width = PtrDiffInfo.first;
612    if (Pointee->isFunctionType())
613      Width *= 2;
614    Align = PtrDiffInfo.second;
615    break;
616  }
617  case Type::Complex: {
618    // Complex types have the same alignment as their elements, but twice the
619    // size.
620    std::pair<uint64_t, unsigned> EltInfo =
621      getTypeInfo(cast<ComplexType>(T)->getElementType());
622    Width = EltInfo.first*2;
623    Align = EltInfo.second;
624    break;
625  }
626  case Type::ObjCInterface: {
627    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
628    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
629    Width = Layout.getSize();
630    Align = Layout.getAlignment();
631    break;
632  }
633  case Type::Record:
634  case Type::Enum: {
635    const TagType *TT = cast<TagType>(T);
636
637    if (TT->getDecl()->isInvalidDecl()) {
638      Width = 1;
639      Align = 1;
640      break;
641    }
642
643    if (const EnumType *ET = dyn_cast<EnumType>(TT))
644      return getTypeInfo(ET->getDecl()->getIntegerType());
645
646    const RecordType *RT = cast<RecordType>(TT);
647    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
648    Width = Layout.getSize();
649    Align = Layout.getAlignment();
650    break;
651  }
652
653  case Type::Typedef: {
654    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
655    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
656      Align = Aligned->getAlignment();
657      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
658    } else
659      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
660    break;
661  }
662
663  case Type::TypeOfExpr:
664    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
665                         .getTypePtr());
666
667  case Type::TypeOf:
668    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
669
670  case Type::Decltype:
671    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
672                        .getTypePtr());
673
674  case Type::QualifiedName:
675    return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
676
677  case Type::TemplateSpecialization:
678    assert(getCanonicalType(T) != T &&
679           "Cannot request the size of a dependent type");
680    // FIXME: this is likely to be wrong once we support template
681    // aliases, since a template alias could refer to a typedef that
682    // has an __aligned__ attribute on it.
683    return getTypeInfo(getCanonicalType(T));
684  }
685
686  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
687  return std::make_pair(Width, Align);
688}
689
690/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
691/// type for the current target in bits.  This can be different than the ABI
692/// alignment in cases where it is beneficial for performance to overalign
693/// a data type.
694unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
695  unsigned ABIAlign = getTypeAlign(T);
696
697  // Double and long long should be naturally aligned if possible.
698  if (const ComplexType* CT = T->getAsComplexType())
699    T = CT->getElementType().getTypePtr();
700  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
701      T->isSpecificBuiltinType(BuiltinType::LongLong))
702    return std::max(ABIAlign, (unsigned)getTypeSize(T));
703
704  return ABIAlign;
705}
706
707
708/// LayoutField - Field layout.
709void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
710                                  bool IsUnion, unsigned StructPacking,
711                                  ASTContext &Context) {
712  unsigned FieldPacking = StructPacking;
713  uint64_t FieldOffset = IsUnion ? 0 : Size;
714  uint64_t FieldSize;
715  unsigned FieldAlign;
716
717  // FIXME: Should this override struct packing? Probably we want to
718  // take the minimum?
719  if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
720    FieldPacking = PA->getAlignment();
721
722  if (const Expr *BitWidthExpr = FD->getBitWidth()) {
723    // TODO: Need to check this algorithm on other targets!
724    //       (tested on Linux-X86)
725    FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
726
727    std::pair<uint64_t, unsigned> FieldInfo =
728      Context.getTypeInfo(FD->getType());
729    uint64_t TypeSize = FieldInfo.first;
730
731    // Determine the alignment of this bitfield. The packing
732    // attributes define a maximum and the alignment attribute defines
733    // a minimum.
734    // FIXME: What is the right behavior when the specified alignment
735    // is smaller than the specified packing?
736    FieldAlign = FieldInfo.second;
737    if (FieldPacking)
738      FieldAlign = std::min(FieldAlign, FieldPacking);
739    if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
740      FieldAlign = std::max(FieldAlign, AA->getAlignment());
741
742    // Check if we need to add padding to give the field the correct
743    // alignment.
744    if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
745      FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
746
747    // Padding members don't affect overall alignment
748    if (!FD->getIdentifier())
749      FieldAlign = 1;
750  } else {
751    if (FD->getType()->isIncompleteArrayType()) {
752      // This is a flexible array member; we can't directly
753      // query getTypeInfo about these, so we figure it out here.
754      // Flexible array members don't have any size, but they
755      // have to be aligned appropriately for their element type.
756      FieldSize = 0;
757      const ArrayType* ATy = Context.getAsArrayType(FD->getType());
758      FieldAlign = Context.getTypeAlign(ATy->getElementType());
759    } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
760      unsigned AS = RT->getPointeeType().getAddressSpace();
761      FieldSize = Context.Target.getPointerWidth(AS);
762      FieldAlign = Context.Target.getPointerAlign(AS);
763    } else {
764      std::pair<uint64_t, unsigned> FieldInfo =
765        Context.getTypeInfo(FD->getType());
766      FieldSize = FieldInfo.first;
767      FieldAlign = FieldInfo.second;
768    }
769
770    // Determine the alignment of this bitfield. The packing
771    // attributes define a maximum and the alignment attribute defines
772    // a minimum. Additionally, the packing alignment must be at least
773    // a byte for non-bitfields.
774    //
775    // FIXME: What is the right behavior when the specified alignment
776    // is smaller than the specified packing?
777    if (FieldPacking)
778      FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
779    if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
780      FieldAlign = std::max(FieldAlign, AA->getAlignment());
781
782    // Round up the current record size to the field's alignment boundary.
783    FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
784  }
785
786  // Place this field at the current location.
787  FieldOffsets[FieldNo] = FieldOffset;
788
789  // Reserve space for this field.
790  if (IsUnion) {
791    Size = std::max(Size, FieldSize);
792  } else {
793    Size = FieldOffset + FieldSize;
794  }
795
796  // Remember the next available offset.
797  NextOffset = Size;
798
799  // Remember max struct/class alignment.
800  Alignment = std::max(Alignment, FieldAlign);
801}
802
803static void CollectLocalObjCIvars(ASTContext *Ctx,
804                                  const ObjCInterfaceDecl *OI,
805                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
806  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
807       E = OI->ivar_end(); I != E; ++I) {
808    ObjCIvarDecl *IVDecl = *I;
809    if (!IVDecl->isInvalidDecl())
810      Fields.push_back(cast<FieldDecl>(IVDecl));
811  }
812}
813
814void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
815                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
816  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
817    CollectObjCIvars(SuperClass, Fields);
818  CollectLocalObjCIvars(this, OI, Fields);
819}
820
821/// ShallowCollectObjCIvars -
822/// Collect all ivars, including those synthesized, in the current class.
823///
824void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
825                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
826                                 bool CollectSynthesized) {
827  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
828         E = OI->ivar_end(); I != E; ++I) {
829     Ivars.push_back(*I);
830  }
831  if (CollectSynthesized)
832    CollectSynthesizedIvars(OI, Ivars);
833}
834
835void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
836                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
837  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
838       E = PD->prop_end(); I != E; ++I)
839    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
840      Ivars.push_back(Ivar);
841
842  // Also look into nested protocols.
843  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
844       E = PD->protocol_end(); P != E; ++P)
845    CollectProtocolSynthesizedIvars(*P, Ivars);
846}
847
848/// CollectSynthesizedIvars -
849/// This routine collect synthesized ivars for the designated class.
850///
851void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
852                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
853  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
854       E = OI->prop_end(); I != E; ++I) {
855    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
856      Ivars.push_back(Ivar);
857  }
858  // Also look into interface's protocol list for properties declared
859  // in the protocol and whose ivars are synthesized.
860  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
861       PE = OI->protocol_end(); P != PE; ++P) {
862    ObjCProtocolDecl *PD = (*P);
863    CollectProtocolSynthesizedIvars(PD, Ivars);
864  }
865}
866
867unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
868  unsigned count = 0;
869  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
870       E = PD->prop_end(); I != E; ++I)
871    if ((*I)->getPropertyIvarDecl())
872      ++count;
873
874  // Also look into nested protocols.
875  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
876       E = PD->protocol_end(); P != E; ++P)
877    count += CountProtocolSynthesizedIvars(*P);
878  return count;
879}
880
881unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
882{
883  unsigned count = 0;
884  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
885       E = OI->prop_end(); I != E; ++I) {
886    if ((*I)->getPropertyIvarDecl())
887      ++count;
888  }
889  // Also look into interface's protocol list for properties declared
890  // in the protocol and whose ivars are synthesized.
891  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
892       PE = OI->protocol_end(); P != PE; ++P) {
893    ObjCProtocolDecl *PD = (*P);
894    count += CountProtocolSynthesizedIvars(PD);
895  }
896  return count;
897}
898
899/// getInterfaceLayoutImpl - Get or compute information about the
900/// layout of the given interface.
901///
902/// \param Impl - If given, also include the layout of the interface's
903/// implementation. This may differ by including synthesized ivars.
904const ASTRecordLayout &
905ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
906                          const ObjCImplementationDecl *Impl) {
907  assert(!D->isForwardDecl() && "Invalid interface decl!");
908
909  // Look up this layout, if already laid out, return what we have.
910  ObjCContainerDecl *Key =
911    Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
912  if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
913    return *Entry;
914
915  unsigned FieldCount = D->ivar_size();
916  // Add in synthesized ivar count if laying out an implementation.
917  if (Impl) {
918    unsigned SynthCount = CountSynthesizedIvars(D);
919    FieldCount += SynthCount;
920    // If there aren't any sythesized ivars then reuse the interface
921    // entry. Note we can't cache this because we simply free all
922    // entries later; however we shouldn't look up implementations
923    // frequently.
924    if (SynthCount == 0)
925      return getObjCLayout(D, 0);
926  }
927
928  ASTRecordLayout *NewEntry = NULL;
929  if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
930    const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
931    unsigned Alignment = SL.getAlignment();
932
933    // We start laying out ivars not at the end of the superclass
934    // structure, but at the next byte following the last field.
935    uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
936
937    ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
938    NewEntry->InitializeLayout(FieldCount);
939  } else {
940    ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
941    NewEntry->InitializeLayout(FieldCount);
942  }
943
944  unsigned StructPacking = 0;
945  if (const PackedAttr *PA = D->getAttr<PackedAttr>())
946    StructPacking = PA->getAlignment();
947
948  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
949    NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
950                                    AA->getAlignment()));
951
952  // Layout each ivar sequentially.
953  unsigned i = 0;
954  llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
955  ShallowCollectObjCIvars(D, Ivars, Impl);
956  for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
957       NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
958
959  // Finally, round the size of the total struct up to the alignment of the
960  // struct itself.
961  NewEntry->FinalizeLayout();
962  return *NewEntry;
963}
964
965const ASTRecordLayout &
966ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
967  return getObjCLayout(D, 0);
968}
969
970const ASTRecordLayout &
971ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
972  return getObjCLayout(D->getClassInterface(), D);
973}
974
975/// getASTRecordLayout - Get or compute information about the layout of the
976/// specified record (struct/union/class), which indicates its size and field
977/// position information.
978const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
979  D = D->getDefinition(*this);
980  assert(D && "Cannot get layout of forward declarations!");
981
982  // Look up this layout, if already laid out, return what we have.
983  const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
984  if (Entry) return *Entry;
985
986  // Allocate and assign into ASTRecordLayouts here.  The "Entry" reference can
987  // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
988  ASTRecordLayout *NewEntry = new ASTRecordLayout();
989  Entry = NewEntry;
990
991  // FIXME: Avoid linear walk through the fields, if possible.
992  NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
993  bool IsUnion = D->isUnion();
994
995  unsigned StructPacking = 0;
996  if (const PackedAttr *PA = D->getAttr<PackedAttr>())
997    StructPacking = PA->getAlignment();
998
999  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
1000    NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
1001                                    AA->getAlignment()));
1002
1003  // Layout each field, for now, just sequentially, respecting alignment.  In
1004  // the future, this will need to be tweakable by targets.
1005  unsigned FieldIdx = 0;
1006  for (RecordDecl::field_iterator Field = D->field_begin(),
1007                               FieldEnd = D->field_end();
1008       Field != FieldEnd; (void)++Field, ++FieldIdx)
1009    NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
1010
1011  // Finally, round the size of the total struct up to the alignment of the
1012  // struct itself.
1013  NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
1014  return *NewEntry;
1015}
1016
1017//===----------------------------------------------------------------------===//
1018//                   Type creation/memoization methods
1019//===----------------------------------------------------------------------===//
1020
1021QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
1022  QualType CanT = getCanonicalType(T);
1023  if (CanT.getAddressSpace() == AddressSpace)
1024    return T;
1025
1026  // If we are composing extended qualifiers together, merge together into one
1027  // ExtQualType node.
1028  unsigned CVRQuals = T.getCVRQualifiers();
1029  QualType::GCAttrTypes GCAttr = QualType::GCNone;
1030  Type *TypeNode = T.getTypePtr();
1031
1032  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1033    // If this type already has an address space specified, it cannot get
1034    // another one.
1035    assert(EQT->getAddressSpace() == 0 &&
1036           "Type cannot be in multiple addr spaces!");
1037    GCAttr = EQT->getObjCGCAttr();
1038    TypeNode = EQT->getBaseType();
1039  }
1040
1041  // Check if we've already instantiated this type.
1042  llvm::FoldingSetNodeID ID;
1043  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
1044  void *InsertPos = 0;
1045  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
1046    return QualType(EXTQy, CVRQuals);
1047
1048  // If the base type isn't canonical, this won't be a canonical type either,
1049  // so fill in the canonical type field.
1050  QualType Canonical;
1051  if (!TypeNode->isCanonical()) {
1052    Canonical = getAddrSpaceQualType(CanT, AddressSpace);
1053
1054    // Update InsertPos, the previous call could have invalidated it.
1055    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1056    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1057  }
1058  ExtQualType *New =
1059    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
1060  ExtQualTypes.InsertNode(New, InsertPos);
1061  Types.push_back(New);
1062  return QualType(New, CVRQuals);
1063}
1064
1065QualType ASTContext::getObjCGCQualType(QualType T,
1066                                       QualType::GCAttrTypes GCAttr) {
1067  QualType CanT = getCanonicalType(T);
1068  if (CanT.getObjCGCAttr() == GCAttr)
1069    return T;
1070
1071  if (T->isPointerType()) {
1072    QualType Pointee = T->getAsPointerType()->getPointeeType();
1073    if (Pointee->isPointerType() || Pointee->isObjCObjectPointerType()) {
1074      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1075      return getPointerType(ResultType);
1076    }
1077  }
1078  // If we are composing extended qualifiers together, merge together into one
1079  // ExtQualType node.
1080  unsigned CVRQuals = T.getCVRQualifiers();
1081  Type *TypeNode = T.getTypePtr();
1082  unsigned AddressSpace = 0;
1083
1084  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1085    // If this type already has an address space specified, it cannot get
1086    // another one.
1087    assert(EQT->getObjCGCAttr() == QualType::GCNone &&
1088           "Type cannot be in multiple addr spaces!");
1089    AddressSpace = EQT->getAddressSpace();
1090    TypeNode = EQT->getBaseType();
1091  }
1092
1093  // Check if we've already instantiated an gc qual'd type of this type.
1094  llvm::FoldingSetNodeID ID;
1095  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
1096  void *InsertPos = 0;
1097  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
1098    return QualType(EXTQy, CVRQuals);
1099
1100  // If the base type isn't canonical, this won't be a canonical type either,
1101  // so fill in the canonical type field.
1102  // FIXME: Isn't this also not canonical if the base type is a array
1103  // or pointer type?  I can't find any documentation for objc_gc, though...
1104  QualType Canonical;
1105  if (!T->isCanonical()) {
1106    Canonical = getObjCGCQualType(CanT, GCAttr);
1107
1108    // Update InsertPos, the previous call could have invalidated it.
1109    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1110    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1111  }
1112  ExtQualType *New =
1113    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
1114  ExtQualTypes.InsertNode(New, InsertPos);
1115  Types.push_back(New);
1116  return QualType(New, CVRQuals);
1117}
1118
1119/// getComplexType - Return the uniqued reference to the type for a complex
1120/// number with the specified element type.
1121QualType ASTContext::getComplexType(QualType T) {
1122  // Unique pointers, to guarantee there is only one pointer of a particular
1123  // structure.
1124  llvm::FoldingSetNodeID ID;
1125  ComplexType::Profile(ID, T);
1126
1127  void *InsertPos = 0;
1128  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1129    return QualType(CT, 0);
1130
1131  // If the pointee type isn't canonical, this won't be a canonical type either,
1132  // so fill in the canonical type field.
1133  QualType Canonical;
1134  if (!T->isCanonical()) {
1135    Canonical = getComplexType(getCanonicalType(T));
1136
1137    // Get the new insert position for the node we care about.
1138    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1139    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1140  }
1141  ComplexType *New = new (*this,8) ComplexType(T, Canonical);
1142  Types.push_back(New);
1143  ComplexTypes.InsertNode(New, InsertPos);
1144  return QualType(New, 0);
1145}
1146
1147QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1148  llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1149     SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1150  FixedWidthIntType *&Entry = Map[Width];
1151  if (!Entry)
1152    Entry = new FixedWidthIntType(Width, Signed);
1153  return QualType(Entry, 0);
1154}
1155
1156/// getPointerType - Return the uniqued reference to the type for a pointer to
1157/// the specified type.
1158QualType ASTContext::getPointerType(QualType T) {
1159  // Unique pointers, to guarantee there is only one pointer of a particular
1160  // structure.
1161  llvm::FoldingSetNodeID ID;
1162  PointerType::Profile(ID, T);
1163
1164  void *InsertPos = 0;
1165  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1166    return QualType(PT, 0);
1167
1168  // If the pointee type isn't canonical, this won't be a canonical type either,
1169  // so fill in the canonical type field.
1170  QualType Canonical;
1171  if (!T->isCanonical()) {
1172    Canonical = getPointerType(getCanonicalType(T));
1173
1174    // Get the new insert position for the node we care about.
1175    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1176    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1177  }
1178  PointerType *New = new (*this,8) PointerType(T, Canonical);
1179  Types.push_back(New);
1180  PointerTypes.InsertNode(New, InsertPos);
1181  return QualType(New, 0);
1182}
1183
1184/// getBlockPointerType - Return the uniqued reference to the type for
1185/// a pointer to the specified block.
1186QualType ASTContext::getBlockPointerType(QualType T) {
1187  assert(T->isFunctionType() && "block of function types only");
1188  // Unique pointers, to guarantee there is only one block of a particular
1189  // structure.
1190  llvm::FoldingSetNodeID ID;
1191  BlockPointerType::Profile(ID, T);
1192
1193  void *InsertPos = 0;
1194  if (BlockPointerType *PT =
1195        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1196    return QualType(PT, 0);
1197
1198  // If the block pointee type isn't canonical, this won't be a canonical
1199  // type either so fill in the canonical type field.
1200  QualType Canonical;
1201  if (!T->isCanonical()) {
1202    Canonical = getBlockPointerType(getCanonicalType(T));
1203
1204    // Get the new insert position for the node we care about.
1205    BlockPointerType *NewIP =
1206      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1207    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1208  }
1209  BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
1210  Types.push_back(New);
1211  BlockPointerTypes.InsertNode(New, InsertPos);
1212  return QualType(New, 0);
1213}
1214
1215/// getLValueReferenceType - Return the uniqued reference to the type for an
1216/// lvalue reference to the specified type.
1217QualType ASTContext::getLValueReferenceType(QualType T) {
1218  // Unique pointers, to guarantee there is only one pointer of a particular
1219  // structure.
1220  llvm::FoldingSetNodeID ID;
1221  ReferenceType::Profile(ID, T);
1222
1223  void *InsertPos = 0;
1224  if (LValueReferenceType *RT =
1225        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1226    return QualType(RT, 0);
1227
1228  // If the referencee type isn't canonical, this won't be a canonical type
1229  // either, so fill in the canonical type field.
1230  QualType Canonical;
1231  if (!T->isCanonical()) {
1232    Canonical = getLValueReferenceType(getCanonicalType(T));
1233
1234    // Get the new insert position for the node we care about.
1235    LValueReferenceType *NewIP =
1236      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1237    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1238  }
1239
1240  LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
1241  Types.push_back(New);
1242  LValueReferenceTypes.InsertNode(New, InsertPos);
1243  return QualType(New, 0);
1244}
1245
1246/// getRValueReferenceType - Return the uniqued reference to the type for an
1247/// rvalue reference to the specified type.
1248QualType ASTContext::getRValueReferenceType(QualType T) {
1249  // Unique pointers, to guarantee there is only one pointer of a particular
1250  // structure.
1251  llvm::FoldingSetNodeID ID;
1252  ReferenceType::Profile(ID, T);
1253
1254  void *InsertPos = 0;
1255  if (RValueReferenceType *RT =
1256        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1257    return QualType(RT, 0);
1258
1259  // If the referencee type isn't canonical, this won't be a canonical type
1260  // either, so fill in the canonical type field.
1261  QualType Canonical;
1262  if (!T->isCanonical()) {
1263    Canonical = getRValueReferenceType(getCanonicalType(T));
1264
1265    // Get the new insert position for the node we care about.
1266    RValueReferenceType *NewIP =
1267      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1268    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1269  }
1270
1271  RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1272  Types.push_back(New);
1273  RValueReferenceTypes.InsertNode(New, InsertPos);
1274  return QualType(New, 0);
1275}
1276
1277/// getMemberPointerType - Return the uniqued reference to the type for a
1278/// member pointer to the specified type, in the specified class.
1279QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1280{
1281  // Unique pointers, to guarantee there is only one pointer of a particular
1282  // structure.
1283  llvm::FoldingSetNodeID ID;
1284  MemberPointerType::Profile(ID, T, Cls);
1285
1286  void *InsertPos = 0;
1287  if (MemberPointerType *PT =
1288      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1289    return QualType(PT, 0);
1290
1291  // If the pointee or class type isn't canonical, this won't be a canonical
1292  // type either, so fill in the canonical type field.
1293  QualType Canonical;
1294  if (!T->isCanonical()) {
1295    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1296
1297    // Get the new insert position for the node we care about.
1298    MemberPointerType *NewIP =
1299      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1300    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1301  }
1302  MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
1303  Types.push_back(New);
1304  MemberPointerTypes.InsertNode(New, InsertPos);
1305  return QualType(New, 0);
1306}
1307
1308/// getConstantArrayType - Return the unique reference to the type for an
1309/// array of the specified element type.
1310QualType ASTContext::getConstantArrayType(QualType EltTy,
1311                                          const llvm::APInt &ArySizeIn,
1312                                          ArrayType::ArraySizeModifier ASM,
1313                                          unsigned EltTypeQuals) {
1314  assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1315         "Constant array of VLAs is illegal!");
1316
1317  // Convert the array size into a canonical width matching the pointer size for
1318  // the target.
1319  llvm::APInt ArySize(ArySizeIn);
1320  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1321
1322  llvm::FoldingSetNodeID ID;
1323  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1324
1325  void *InsertPos = 0;
1326  if (ConstantArrayType *ATP =
1327      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1328    return QualType(ATP, 0);
1329
1330  // If the element type isn't canonical, this won't be a canonical type either,
1331  // so fill in the canonical type field.
1332  QualType Canonical;
1333  if (!EltTy->isCanonical()) {
1334    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1335                                     ASM, EltTypeQuals);
1336    // Get the new insert position for the node we care about.
1337    ConstantArrayType *NewIP =
1338      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1339    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1340  }
1341
1342  ConstantArrayType *New =
1343    new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1344  ConstantArrayTypes.InsertNode(New, InsertPos);
1345  Types.push_back(New);
1346  return QualType(New, 0);
1347}
1348
1349/// getConstantArrayWithExprType - Return a reference to the type for
1350/// an array of the specified element type.
1351QualType
1352ASTContext::getConstantArrayWithExprType(QualType EltTy,
1353                                         const llvm::APInt &ArySizeIn,
1354                                         Expr *ArySizeExpr,
1355                                         ArrayType::ArraySizeModifier ASM,
1356                                         unsigned EltTypeQuals,
1357                                         SourceRange Brackets) {
1358  // Convert the array size into a canonical width matching the pointer
1359  // size for the target.
1360  llvm::APInt ArySize(ArySizeIn);
1361  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1362
1363  // Compute the canonical ConstantArrayType.
1364  QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1365                                            ArySize, ASM, EltTypeQuals);
1366  // Since we don't unique expressions, it isn't possible to unique VLA's
1367  // that have an expression provided for their size.
1368  ConstantArrayWithExprType *New =
1369    new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1370                                          ArySize, ArySizeExpr,
1371                                          ASM, EltTypeQuals, Brackets);
1372  Types.push_back(New);
1373  return QualType(New, 0);
1374}
1375
1376/// getConstantArrayWithoutExprType - Return a reference to the type for
1377/// an array of the specified element type.
1378QualType
1379ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1380                                            const llvm::APInt &ArySizeIn,
1381                                            ArrayType::ArraySizeModifier ASM,
1382                                            unsigned EltTypeQuals) {
1383  // Convert the array size into a canonical width matching the pointer
1384  // size for the target.
1385  llvm::APInt ArySize(ArySizeIn);
1386  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1387
1388  // Compute the canonical ConstantArrayType.
1389  QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1390                                            ArySize, ASM, EltTypeQuals);
1391  ConstantArrayWithoutExprType *New =
1392    new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1393                                             ArySize, ASM, EltTypeQuals);
1394  Types.push_back(New);
1395  return QualType(New, 0);
1396}
1397
1398/// getVariableArrayType - Returns a non-unique reference to the type for a
1399/// variable array of the specified element type.
1400QualType ASTContext::getVariableArrayType(QualType EltTy,
1401                                          Expr *NumElts,
1402                                          ArrayType::ArraySizeModifier ASM,
1403                                          unsigned EltTypeQuals,
1404                                          SourceRange Brackets) {
1405  // Since we don't unique expressions, it isn't possible to unique VLA's
1406  // that have an expression provided for their size.
1407
1408  VariableArrayType *New =
1409    new(*this,8)VariableArrayType(EltTy, QualType(),
1410                                  NumElts, ASM, EltTypeQuals, Brackets);
1411
1412  VariableArrayTypes.push_back(New);
1413  Types.push_back(New);
1414  return QualType(New, 0);
1415}
1416
1417/// getDependentSizedArrayType - Returns a non-unique reference to
1418/// the type for a dependently-sized array of the specified element
1419/// type. FIXME: We will need these to be uniqued, or at least
1420/// comparable, at some point.
1421QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1422                                                Expr *NumElts,
1423                                                ArrayType::ArraySizeModifier ASM,
1424                                                unsigned EltTypeQuals,
1425                                                SourceRange Brackets) {
1426  assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1427         "Size must be type- or value-dependent!");
1428
1429  // Since we don't unique expressions, it isn't possible to unique
1430  // dependently-sized array types.
1431
1432  DependentSizedArrayType *New =
1433    new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1434                                          NumElts, ASM, EltTypeQuals,
1435                                          Brackets);
1436
1437  DependentSizedArrayTypes.push_back(New);
1438  Types.push_back(New);
1439  return QualType(New, 0);
1440}
1441
1442QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1443                                            ArrayType::ArraySizeModifier ASM,
1444                                            unsigned EltTypeQuals) {
1445  llvm::FoldingSetNodeID ID;
1446  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1447
1448  void *InsertPos = 0;
1449  if (IncompleteArrayType *ATP =
1450       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1451    return QualType(ATP, 0);
1452
1453  // If the element type isn't canonical, this won't be a canonical type
1454  // either, so fill in the canonical type field.
1455  QualType Canonical;
1456
1457  if (!EltTy->isCanonical()) {
1458    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1459                                       ASM, EltTypeQuals);
1460
1461    // Get the new insert position for the node we care about.
1462    IncompleteArrayType *NewIP =
1463      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1464    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1465  }
1466
1467  IncompleteArrayType *New
1468    = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1469                                        ASM, EltTypeQuals);
1470
1471  IncompleteArrayTypes.InsertNode(New, InsertPos);
1472  Types.push_back(New);
1473  return QualType(New, 0);
1474}
1475
1476/// getVectorType - Return the unique reference to a vector type of
1477/// the specified element type and size. VectorType must be a built-in type.
1478QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1479  BuiltinType *baseType;
1480
1481  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1482  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1483
1484  // Check if we've already instantiated a vector of this type.
1485  llvm::FoldingSetNodeID ID;
1486  VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1487  void *InsertPos = 0;
1488  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1489    return QualType(VTP, 0);
1490
1491  // If the element type isn't canonical, this won't be a canonical type either,
1492  // so fill in the canonical type field.
1493  QualType Canonical;
1494  if (!vecType->isCanonical()) {
1495    Canonical = getVectorType(getCanonicalType(vecType), NumElts);
1496
1497    // Get the new insert position for the node we care about.
1498    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1499    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1500  }
1501  VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
1502  VectorTypes.InsertNode(New, InsertPos);
1503  Types.push_back(New);
1504  return QualType(New, 0);
1505}
1506
1507/// getExtVectorType - Return the unique reference to an extended vector type of
1508/// the specified element type and size. VectorType must be a built-in type.
1509QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1510  BuiltinType *baseType;
1511
1512  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1513  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1514
1515  // Check if we've already instantiated a vector of this type.
1516  llvm::FoldingSetNodeID ID;
1517  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
1518  void *InsertPos = 0;
1519  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1520    return QualType(VTP, 0);
1521
1522  // If the element type isn't canonical, this won't be a canonical type either,
1523  // so fill in the canonical type field.
1524  QualType Canonical;
1525  if (!vecType->isCanonical()) {
1526    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1527
1528    // Get the new insert position for the node we care about.
1529    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1530    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1531  }
1532  ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
1533  VectorTypes.InsertNode(New, InsertPos);
1534  Types.push_back(New);
1535  return QualType(New, 0);
1536}
1537
1538QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1539                                                    Expr *SizeExpr,
1540                                                    SourceLocation AttrLoc) {
1541  DependentSizedExtVectorType *New =
1542      new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1543                                                SizeExpr, AttrLoc);
1544
1545  DependentSizedExtVectorTypes.push_back(New);
1546  Types.push_back(New);
1547  return QualType(New, 0);
1548}
1549
1550/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1551///
1552QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
1553  // Unique functions, to guarantee there is only one function of a particular
1554  // structure.
1555  llvm::FoldingSetNodeID ID;
1556  FunctionNoProtoType::Profile(ID, ResultTy);
1557
1558  void *InsertPos = 0;
1559  if (FunctionNoProtoType *FT =
1560        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1561    return QualType(FT, 0);
1562
1563  QualType Canonical;
1564  if (!ResultTy->isCanonical()) {
1565    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
1566
1567    // Get the new insert position for the node we care about.
1568    FunctionNoProtoType *NewIP =
1569      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1570    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1571  }
1572
1573  FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
1574  Types.push_back(New);
1575  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1576  return QualType(New, 0);
1577}
1578
1579/// getFunctionType - Return a normal function type with a typed argument
1580/// list.  isVariadic indicates whether the argument list includes '...'.
1581QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1582                                     unsigned NumArgs, bool isVariadic,
1583                                     unsigned TypeQuals, bool hasExceptionSpec,
1584                                     bool hasAnyExceptionSpec, unsigned NumExs,
1585                                     const QualType *ExArray) {
1586  // Unique functions, to guarantee there is only one function of a particular
1587  // structure.
1588  llvm::FoldingSetNodeID ID;
1589  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1590                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1591                             NumExs, ExArray);
1592
1593  void *InsertPos = 0;
1594  if (FunctionProtoType *FTP =
1595        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1596    return QualType(FTP, 0);
1597
1598  // Determine whether the type being created is already canonical or not.
1599  bool isCanonical = ResultTy->isCanonical();
1600  if (hasExceptionSpec)
1601    isCanonical = false;
1602  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1603    if (!ArgArray[i]->isCanonical())
1604      isCanonical = false;
1605
1606  // If this type isn't canonical, get the canonical version of it.
1607  // The exception spec is not part of the canonical type.
1608  QualType Canonical;
1609  if (!isCanonical) {
1610    llvm::SmallVector<QualType, 16> CanonicalArgs;
1611    CanonicalArgs.reserve(NumArgs);
1612    for (unsigned i = 0; i != NumArgs; ++i)
1613      CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
1614
1615    Canonical = getFunctionType(getCanonicalType(ResultTy),
1616                                CanonicalArgs.data(), NumArgs,
1617                                isVariadic, TypeQuals);
1618
1619    // Get the new insert position for the node we care about.
1620    FunctionProtoType *NewIP =
1621      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1622    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1623  }
1624
1625  // FunctionProtoType objects are allocated with extra bytes after them
1626  // for two variable size arrays (for parameter and exception types) at the
1627  // end of them.
1628  FunctionProtoType *FTP =
1629    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1630                                 NumArgs*sizeof(QualType) +
1631                                 NumExs*sizeof(QualType), 8);
1632  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1633                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1634                              ExArray, NumExs, Canonical);
1635  Types.push_back(FTP);
1636  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1637  return QualType(FTP, 0);
1638}
1639
1640/// getTypeDeclType - Return the unique reference to the type for the
1641/// specified type declaration.
1642QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1643  assert(Decl && "Passed null for Decl param");
1644  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1645
1646  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1647    return getTypedefType(Typedef);
1648  else if (isa<TemplateTypeParmDecl>(Decl)) {
1649    assert(false && "Template type parameter types are always available.");
1650  } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
1651    return getObjCInterfaceType(ObjCInterface);
1652
1653  if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1654    if (PrevDecl)
1655      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1656    else
1657      Decl->TypeForDecl = new (*this,8) RecordType(Record);
1658  }
1659  else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1660    if (PrevDecl)
1661      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1662    else
1663      Decl->TypeForDecl = new (*this,8) EnumType(Enum);
1664  }
1665  else
1666    assert(false && "TypeDecl without a type?");
1667
1668  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1669  return QualType(Decl->TypeForDecl, 0);
1670}
1671
1672/// getTypedefType - Return the unique reference to the type for the
1673/// specified typename decl.
1674QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1675  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1676
1677  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1678  Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
1679  Types.push_back(Decl->TypeForDecl);
1680  return QualType(Decl->TypeForDecl, 0);
1681}
1682
1683/// getObjCInterfaceType - Return the unique reference to the type for the
1684/// specified ObjC interface decl.
1685QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
1686  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1687
1688  ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1689  Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
1690  Types.push_back(Decl->TypeForDecl);
1691  return QualType(Decl->TypeForDecl, 0);
1692}
1693
1694/// \brief Retrieve the template type parameter type for a template
1695/// parameter or parameter pack with the given depth, index, and (optionally)
1696/// name.
1697QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1698                                             bool ParameterPack,
1699                                             IdentifierInfo *Name) {
1700  llvm::FoldingSetNodeID ID;
1701  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1702  void *InsertPos = 0;
1703  TemplateTypeParmType *TypeParm
1704    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1705
1706  if (TypeParm)
1707    return QualType(TypeParm, 0);
1708
1709  if (Name) {
1710    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1711    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1712                                                   Name, Canon);
1713  } else
1714    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
1715
1716  Types.push_back(TypeParm);
1717  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1718
1719  return QualType(TypeParm, 0);
1720}
1721
1722QualType
1723ASTContext::getTemplateSpecializationType(TemplateName Template,
1724                                          const TemplateArgument *Args,
1725                                          unsigned NumArgs,
1726                                          QualType Canon) {
1727  if (!Canon.isNull())
1728    Canon = getCanonicalType(Canon);
1729
1730  llvm::FoldingSetNodeID ID;
1731  TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
1732
1733  void *InsertPos = 0;
1734  TemplateSpecializationType *Spec
1735    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1736
1737  if (Spec)
1738    return QualType(Spec, 0);
1739
1740  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1741                        sizeof(TemplateArgument) * NumArgs),
1742                       8);
1743  Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
1744  Types.push_back(Spec);
1745  TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1746
1747  return QualType(Spec, 0);
1748}
1749
1750QualType
1751ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
1752                                 QualType NamedType) {
1753  llvm::FoldingSetNodeID ID;
1754  QualifiedNameType::Profile(ID, NNS, NamedType);
1755
1756  void *InsertPos = 0;
1757  QualifiedNameType *T
1758    = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1759  if (T)
1760    return QualType(T, 0);
1761
1762  T = new (*this) QualifiedNameType(NNS, NamedType,
1763                                    getCanonicalType(NamedType));
1764  Types.push_back(T);
1765  QualifiedNameTypes.InsertNode(T, InsertPos);
1766  return QualType(T, 0);
1767}
1768
1769QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1770                                     const IdentifierInfo *Name,
1771                                     QualType Canon) {
1772  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1773
1774  if (Canon.isNull()) {
1775    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1776    if (CanonNNS != NNS)
1777      Canon = getTypenameType(CanonNNS, Name);
1778  }
1779
1780  llvm::FoldingSetNodeID ID;
1781  TypenameType::Profile(ID, NNS, Name);
1782
1783  void *InsertPos = 0;
1784  TypenameType *T
1785    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1786  if (T)
1787    return QualType(T, 0);
1788
1789  T = new (*this) TypenameType(NNS, Name, Canon);
1790  Types.push_back(T);
1791  TypenameTypes.InsertNode(T, InsertPos);
1792  return QualType(T, 0);
1793}
1794
1795QualType
1796ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1797                            const TemplateSpecializationType *TemplateId,
1798                            QualType Canon) {
1799  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1800
1801  if (Canon.isNull()) {
1802    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1803    QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1804    if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1805      const TemplateSpecializationType *CanonTemplateId
1806        = CanonType->getAsTemplateSpecializationType();
1807      assert(CanonTemplateId &&
1808             "Canonical type must also be a template specialization type");
1809      Canon = getTypenameType(CanonNNS, CanonTemplateId);
1810    }
1811  }
1812
1813  llvm::FoldingSetNodeID ID;
1814  TypenameType::Profile(ID, NNS, TemplateId);
1815
1816  void *InsertPos = 0;
1817  TypenameType *T
1818    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1819  if (T)
1820    return QualType(T, 0);
1821
1822  T = new (*this) TypenameType(NNS, TemplateId, Canon);
1823  Types.push_back(T);
1824  TypenameTypes.InsertNode(T, InsertPos);
1825  return QualType(T, 0);
1826}
1827
1828/// CmpProtocolNames - Comparison predicate for sorting protocols
1829/// alphabetically.
1830static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1831                            const ObjCProtocolDecl *RHS) {
1832  return LHS->getDeclName() < RHS->getDeclName();
1833}
1834
1835static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1836                                   unsigned &NumProtocols) {
1837  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1838
1839  // Sort protocols, keyed by name.
1840  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1841
1842  // Remove duplicates.
1843  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1844  NumProtocols = ProtocolsEnd-Protocols;
1845}
1846
1847/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1848/// the given interface decl and the conforming protocol list.
1849QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
1850                                              ObjCProtocolDecl **Protocols,
1851                                              unsigned NumProtocols) {
1852  if (InterfaceT.isNull())
1853    InterfaceT = QualType(ObjCObjectPointerType::getIdInterface(), 0);
1854
1855  // Sort the protocol list alphabetically to canonicalize it.
1856  if (NumProtocols)
1857    SortAndUniqueProtocols(Protocols, NumProtocols);
1858
1859  llvm::FoldingSetNodeID ID;
1860  ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
1861
1862  void *InsertPos = 0;
1863  if (ObjCObjectPointerType *QT =
1864              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1865    return QualType(QT, 0);
1866
1867  // No Match;
1868  ObjCObjectPointerType *QType =
1869    new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
1870
1871  Types.push_back(QType);
1872  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1873  return QualType(QType, 0);
1874}
1875
1876/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1877/// the given interface decl and the conforming protocol list.
1878QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1879                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
1880  // Sort the protocol list alphabetically to canonicalize it.
1881  SortAndUniqueProtocols(Protocols, NumProtocols);
1882
1883  llvm::FoldingSetNodeID ID;
1884  ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
1885
1886  void *InsertPos = 0;
1887  if (ObjCQualifiedInterfaceType *QT =
1888      ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
1889    return QualType(QT, 0);
1890
1891  // No Match;
1892  ObjCQualifiedInterfaceType *QType =
1893    new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
1894
1895  Types.push_back(QType);
1896  ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
1897  return QualType(QType, 0);
1898}
1899
1900/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1901/// TypeOfExprType AST's (since expression's are never shared). For example,
1902/// multiple declarations that refer to "typeof(x)" all contain different
1903/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1904/// on canonical type's (which are always unique).
1905QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
1906  TypeOfExprType *toe;
1907  if (tofExpr->isTypeDependent())
1908    toe = new (*this, 8) TypeOfExprType(tofExpr);
1909  else {
1910    QualType Canonical = getCanonicalType(tofExpr->getType());
1911    toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1912  }
1913  Types.push_back(toe);
1914  return QualType(toe, 0);
1915}
1916
1917/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
1918/// TypeOfType AST's. The only motivation to unique these nodes would be
1919/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1920/// an issue. This doesn't effect the type checker, since it operates
1921/// on canonical type's (which are always unique).
1922QualType ASTContext::getTypeOfType(QualType tofType) {
1923  QualType Canonical = getCanonicalType(tofType);
1924  TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
1925  Types.push_back(tot);
1926  return QualType(tot, 0);
1927}
1928
1929/// getDecltypeForExpr - Given an expr, will return the decltype for that
1930/// expression, according to the rules in C++0x [dcl.type.simple]p4
1931static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
1932  if (e->isTypeDependent())
1933    return Context.DependentTy;
1934
1935  // If e is an id expression or a class member access, decltype(e) is defined
1936  // as the type of the entity named by e.
1937  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1938    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1939      return VD->getType();
1940  }
1941  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1942    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1943      return FD->getType();
1944  }
1945  // If e is a function call or an invocation of an overloaded operator,
1946  // (parentheses around e are ignored), decltype(e) is defined as the
1947  // return type of that function.
1948  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1949    return CE->getCallReturnType();
1950
1951  QualType T = e->getType();
1952
1953  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1954  // defined as T&, otherwise decltype(e) is defined as T.
1955  if (e->isLvalue(Context) == Expr::LV_Valid)
1956    T = Context.getLValueReferenceType(T);
1957
1958  return T;
1959}
1960
1961/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
1962/// DecltypeType AST's. The only motivation to unique these nodes would be
1963/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1964/// an issue. This doesn't effect the type checker, since it operates
1965/// on canonical type's (which are always unique).
1966QualType ASTContext::getDecltypeType(Expr *e) {
1967  DecltypeType *dt;
1968  if (e->isTypeDependent()) // FIXME: canonicalize the expression
1969    dt = new (*this, 8) DecltypeType(e, DependentTy);
1970  else {
1971    QualType T = getDecltypeForExpr(e, *this);
1972    dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
1973  }
1974  Types.push_back(dt);
1975  return QualType(dt, 0);
1976}
1977
1978/// getTagDeclType - Return the unique reference to the type for the
1979/// specified TagDecl (struct/union/class/enum) decl.
1980QualType ASTContext::getTagDeclType(TagDecl *Decl) {
1981  assert (Decl);
1982  return getTypeDeclType(Decl);
1983}
1984
1985/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1986/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1987/// needs to agree with the definition in <stddef.h>.
1988QualType ASTContext::getSizeType() const {
1989  return getFromTargetType(Target.getSizeType());
1990}
1991
1992/// getSignedWCharType - Return the type of "signed wchar_t".
1993/// Used when in C++, as a GCC extension.
1994QualType ASTContext::getSignedWCharType() const {
1995  // FIXME: derive from "Target" ?
1996  return WCharTy;
1997}
1998
1999/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2000/// Used when in C++, as a GCC extension.
2001QualType ASTContext::getUnsignedWCharType() const {
2002  // FIXME: derive from "Target" ?
2003  return UnsignedIntTy;
2004}
2005
2006/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2007/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2008QualType ASTContext::getPointerDiffType() const {
2009  return getFromTargetType(Target.getPtrDiffType(0));
2010}
2011
2012//===----------------------------------------------------------------------===//
2013//                              Type Operators
2014//===----------------------------------------------------------------------===//
2015
2016/// getCanonicalType - Return the canonical (structural) type corresponding to
2017/// the specified potentially non-canonical type.  The non-canonical version
2018/// of a type may have many "decorated" versions of types.  Decorators can
2019/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2020/// to be free of any of these, allowing two canonical types to be compared
2021/// for exact equality with a simple pointer comparison.
2022QualType ASTContext::getCanonicalType(QualType T) {
2023  QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
2024
2025  // If the result has type qualifiers, make sure to canonicalize them as well.
2026  unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
2027  if (TypeQuals == 0) return CanType;
2028
2029  // If the type qualifiers are on an array type, get the canonical type of the
2030  // array with the qualifiers applied to the element type.
2031  ArrayType *AT = dyn_cast<ArrayType>(CanType);
2032  if (!AT)
2033    return CanType.getQualifiedType(TypeQuals);
2034
2035  // Get the canonical version of the element with the extra qualifiers on it.
2036  // This can recursively sink qualifiers through multiple levels of arrays.
2037  QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2038  NewEltTy = getCanonicalType(NewEltTy);
2039
2040  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2041    return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
2042                                CAT->getIndexTypeQualifier());
2043  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2044    return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2045                                  IAT->getIndexTypeQualifier());
2046
2047  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
2048    return getDependentSizedArrayType(NewEltTy,
2049                                      DSAT->getSizeExpr(),
2050                                      DSAT->getSizeModifier(),
2051                                      DSAT->getIndexTypeQualifier(),
2052                                      DSAT->getBracketsRange());
2053
2054  VariableArrayType *VAT = cast<VariableArrayType>(AT);
2055  return getVariableArrayType(NewEltTy,
2056                              VAT->getSizeExpr(),
2057                              VAT->getSizeModifier(),
2058                              VAT->getIndexTypeQualifier(),
2059                              VAT->getBracketsRange());
2060}
2061
2062Decl *ASTContext::getCanonicalDecl(Decl *D) {
2063  if (!D)
2064    return 0;
2065
2066  if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
2067    QualType T = getTagDeclType(Tag);
2068    return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
2069                         ->getDecl());
2070  }
2071
2072  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
2073    while (Template->getPreviousDeclaration())
2074      Template = Template->getPreviousDeclaration();
2075    return Template;
2076  }
2077
2078  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2079    while (Function->getPreviousDeclaration())
2080      Function = Function->getPreviousDeclaration();
2081    return const_cast<FunctionDecl *>(Function);
2082  }
2083
2084  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2085    while (FunTmpl->getPreviousDeclaration())
2086      FunTmpl = FunTmpl->getPreviousDeclaration();
2087    return FunTmpl;
2088  }
2089
2090  if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
2091    while (Var->getPreviousDeclaration())
2092      Var = Var->getPreviousDeclaration();
2093    return const_cast<VarDecl *>(Var);
2094  }
2095
2096  return D;
2097}
2098
2099TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2100  // If this template name refers to a template, the canonical
2101  // template name merely stores the template itself.
2102  if (TemplateDecl *Template = Name.getAsTemplateDecl())
2103    return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
2104
2105  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2106  assert(DTN && "Non-dependent template names must refer to template decls.");
2107  return DTN->CanonicalTemplateName;
2108}
2109
2110NestedNameSpecifier *
2111ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2112  if (!NNS)
2113    return 0;
2114
2115  switch (NNS->getKind()) {
2116  case NestedNameSpecifier::Identifier:
2117    // Canonicalize the prefix but keep the identifier the same.
2118    return NestedNameSpecifier::Create(*this,
2119                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2120                                       NNS->getAsIdentifier());
2121
2122  case NestedNameSpecifier::Namespace:
2123    // A namespace is canonical; build a nested-name-specifier with
2124    // this namespace and no prefix.
2125    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2126
2127  case NestedNameSpecifier::TypeSpec:
2128  case NestedNameSpecifier::TypeSpecWithTemplate: {
2129    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2130    NestedNameSpecifier *Prefix = 0;
2131
2132    // FIXME: This isn't the right check!
2133    if (T->isDependentType())
2134      Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2135
2136    return NestedNameSpecifier::Create(*this, Prefix,
2137                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2138                                       T.getTypePtr());
2139  }
2140
2141  case NestedNameSpecifier::Global:
2142    // The global specifier is canonical and unique.
2143    return NNS;
2144  }
2145
2146  // Required to silence a GCC warning
2147  return 0;
2148}
2149
2150
2151const ArrayType *ASTContext::getAsArrayType(QualType T) {
2152  // Handle the non-qualified case efficiently.
2153  if (T.getCVRQualifiers() == 0) {
2154    // Handle the common positive case fast.
2155    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2156      return AT;
2157  }
2158
2159  // Handle the common negative case fast, ignoring CVR qualifiers.
2160  QualType CType = T->getCanonicalTypeInternal();
2161
2162  // Make sure to look through type qualifiers (like ExtQuals) for the negative
2163  // test.
2164  if (!isa<ArrayType>(CType) &&
2165      !isa<ArrayType>(CType.getUnqualifiedType()))
2166    return 0;
2167
2168  // Apply any CVR qualifiers from the array type to the element type.  This
2169  // implements C99 6.7.3p8: "If the specification of an array type includes
2170  // any type qualifiers, the element type is so qualified, not the array type."
2171
2172  // If we get here, we either have type qualifiers on the type, or we have
2173  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2174  // we must propagate them down into the elemeng type.
2175  unsigned CVRQuals = T.getCVRQualifiers();
2176  unsigned AddrSpace = 0;
2177  Type *Ty = T.getTypePtr();
2178
2179  // Rip through ExtQualType's and typedefs to get to a concrete type.
2180  while (1) {
2181    if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2182      AddrSpace = EXTQT->getAddressSpace();
2183      Ty = EXTQT->getBaseType();
2184    } else {
2185      T = Ty->getDesugaredType();
2186      if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2187        break;
2188      CVRQuals |= T.getCVRQualifiers();
2189      Ty = T.getTypePtr();
2190    }
2191  }
2192
2193  // If we have a simple case, just return now.
2194  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2195  if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2196    return ATy;
2197
2198  // Otherwise, we have an array and we have qualifiers on it.  Push the
2199  // qualifiers into the array element type and return a new array type.
2200  // Get the canonical version of the element with the extra qualifiers on it.
2201  // This can recursively sink qualifiers through multiple levels of arrays.
2202  QualType NewEltTy = ATy->getElementType();
2203  if (AddrSpace)
2204    NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
2205  NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2206
2207  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2208    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2209                                                CAT->getSizeModifier(),
2210                                                CAT->getIndexTypeQualifier()));
2211  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2212    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2213                                                  IAT->getSizeModifier(),
2214                                                  IAT->getIndexTypeQualifier()));
2215
2216  if (const DependentSizedArrayType *DSAT
2217        = dyn_cast<DependentSizedArrayType>(ATy))
2218    return cast<ArrayType>(
2219                     getDependentSizedArrayType(NewEltTy,
2220                                                DSAT->getSizeExpr(),
2221                                                DSAT->getSizeModifier(),
2222                                                DSAT->getIndexTypeQualifier(),
2223                                                DSAT->getBracketsRange()));
2224
2225  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2226  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2227                                              VAT->getSizeExpr(),
2228                                              VAT->getSizeModifier(),
2229                                              VAT->getIndexTypeQualifier(),
2230                                              VAT->getBracketsRange()));
2231}
2232
2233
2234/// getArrayDecayedType - Return the properly qualified result of decaying the
2235/// specified array type to a pointer.  This operation is non-trivial when
2236/// handling typedefs etc.  The canonical type of "T" must be an array type,
2237/// this returns a pointer to a properly qualified element of the array.
2238///
2239/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2240QualType ASTContext::getArrayDecayedType(QualType Ty) {
2241  // Get the element type with 'getAsArrayType' so that we don't lose any
2242  // typedefs in the element type of the array.  This also handles propagation
2243  // of type qualifiers from the array type into the element type if present
2244  // (C99 6.7.3p8).
2245  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2246  assert(PrettyArrayType && "Not an array type!");
2247
2248  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2249
2250  // int x[restrict 4] ->  int *restrict
2251  return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
2252}
2253
2254QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
2255  QualType ElemTy = VAT->getElementType();
2256
2257  if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2258    return getBaseElementType(VAT);
2259
2260  return ElemTy;
2261}
2262
2263/// getFloatingRank - Return a relative rank for floating point types.
2264/// This routine will assert if passed a built-in type that isn't a float.
2265static FloatingRank getFloatingRank(QualType T) {
2266  if (const ComplexType *CT = T->getAsComplexType())
2267    return getFloatingRank(CT->getElementType());
2268
2269  assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
2270  switch (T->getAsBuiltinType()->getKind()) {
2271  default: assert(0 && "getFloatingRank(): not a floating type");
2272  case BuiltinType::Float:      return FloatRank;
2273  case BuiltinType::Double:     return DoubleRank;
2274  case BuiltinType::LongDouble: return LongDoubleRank;
2275  }
2276}
2277
2278/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2279/// point or a complex type (based on typeDomain/typeSize).
2280/// 'typeDomain' is a real floating point or complex type.
2281/// 'typeSize' is a real floating point or complex type.
2282QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2283                                                       QualType Domain) const {
2284  FloatingRank EltRank = getFloatingRank(Size);
2285  if (Domain->isComplexType()) {
2286    switch (EltRank) {
2287    default: assert(0 && "getFloatingRank(): illegal value for rank");
2288    case FloatRank:      return FloatComplexTy;
2289    case DoubleRank:     return DoubleComplexTy;
2290    case LongDoubleRank: return LongDoubleComplexTy;
2291    }
2292  }
2293
2294  assert(Domain->isRealFloatingType() && "Unknown domain!");
2295  switch (EltRank) {
2296  default: assert(0 && "getFloatingRank(): illegal value for rank");
2297  case FloatRank:      return FloatTy;
2298  case DoubleRank:     return DoubleTy;
2299  case LongDoubleRank: return LongDoubleTy;
2300  }
2301}
2302
2303/// getFloatingTypeOrder - Compare the rank of the two specified floating
2304/// point types, ignoring the domain of the type (i.e. 'double' ==
2305/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2306/// LHS < RHS, return -1.
2307int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2308  FloatingRank LHSR = getFloatingRank(LHS);
2309  FloatingRank RHSR = getFloatingRank(RHS);
2310
2311  if (LHSR == RHSR)
2312    return 0;
2313  if (LHSR > RHSR)
2314    return 1;
2315  return -1;
2316}
2317
2318/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2319/// routine will assert if passed a built-in type that isn't an integer or enum,
2320/// or if it is not canonicalized.
2321unsigned ASTContext::getIntegerRank(Type *T) {
2322  assert(T->isCanonical() && "T should be canonicalized");
2323  if (EnumType* ET = dyn_cast<EnumType>(T))
2324    T = ET->getDecl()->getIntegerType().getTypePtr();
2325
2326  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2327    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2328
2329  // There are two things which impact the integer rank: the width, and
2330  // the ordering of builtins.  The builtin ordering is encoded in the
2331  // bottom three bits; the width is encoded in the bits above that.
2332  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
2333    return FWIT->getWidth() << 3;
2334
2335  switch (cast<BuiltinType>(T)->getKind()) {
2336  default: assert(0 && "getIntegerRank(): not a built-in integer");
2337  case BuiltinType::Bool:
2338    return 1 + (getIntWidth(BoolTy) << 3);
2339  case BuiltinType::Char_S:
2340  case BuiltinType::Char_U:
2341  case BuiltinType::SChar:
2342  case BuiltinType::UChar:
2343    return 2 + (getIntWidth(CharTy) << 3);
2344  case BuiltinType::Short:
2345  case BuiltinType::UShort:
2346    return 3 + (getIntWidth(ShortTy) << 3);
2347  case BuiltinType::Int:
2348  case BuiltinType::UInt:
2349    return 4 + (getIntWidth(IntTy) << 3);
2350  case BuiltinType::Long:
2351  case BuiltinType::ULong:
2352    return 5 + (getIntWidth(LongTy) << 3);
2353  case BuiltinType::LongLong:
2354  case BuiltinType::ULongLong:
2355    return 6 + (getIntWidth(LongLongTy) << 3);
2356  case BuiltinType::Int128:
2357  case BuiltinType::UInt128:
2358    return 7 + (getIntWidth(Int128Ty) << 3);
2359  }
2360}
2361
2362/// getIntegerTypeOrder - Returns the highest ranked integer type:
2363/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2364/// LHS < RHS, return -1.
2365int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2366  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2367  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2368  if (LHSC == RHSC) return 0;
2369
2370  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2371  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2372
2373  unsigned LHSRank = getIntegerRank(LHSC);
2374  unsigned RHSRank = getIntegerRank(RHSC);
2375
2376  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2377    if (LHSRank == RHSRank) return 0;
2378    return LHSRank > RHSRank ? 1 : -1;
2379  }
2380
2381  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2382  if (LHSUnsigned) {
2383    // If the unsigned [LHS] type is larger, return it.
2384    if (LHSRank >= RHSRank)
2385      return 1;
2386
2387    // If the signed type can represent all values of the unsigned type, it
2388    // wins.  Because we are dealing with 2's complement and types that are
2389    // powers of two larger than each other, this is always safe.
2390    return -1;
2391  }
2392
2393  // If the unsigned [RHS] type is larger, return it.
2394  if (RHSRank >= LHSRank)
2395    return -1;
2396
2397  // If the signed type can represent all values of the unsigned type, it
2398  // wins.  Because we are dealing with 2's complement and types that are
2399  // powers of two larger than each other, this is always safe.
2400  return 1;
2401}
2402
2403// getCFConstantStringType - Return the type used for constant CFStrings.
2404QualType ASTContext::getCFConstantStringType() {
2405  if (!CFConstantStringTypeDecl) {
2406    CFConstantStringTypeDecl =
2407      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2408                         &Idents.get("NSConstantString"));
2409    QualType FieldTypes[4];
2410
2411    // const int *isa;
2412    FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
2413    // int flags;
2414    FieldTypes[1] = IntTy;
2415    // const char *str;
2416    FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
2417    // long length;
2418    FieldTypes[3] = LongTy;
2419
2420    // Create fields
2421    for (unsigned i = 0; i < 4; ++i) {
2422      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2423                                           SourceLocation(), 0,
2424                                           FieldTypes[i], /*BitWidth=*/0,
2425                                           /*Mutable=*/false);
2426      CFConstantStringTypeDecl->addDecl(Field);
2427    }
2428
2429    CFConstantStringTypeDecl->completeDefinition(*this);
2430  }
2431
2432  return getTagDeclType(CFConstantStringTypeDecl);
2433}
2434
2435void ASTContext::setCFConstantStringType(QualType T) {
2436  const RecordType *Rec = T->getAsRecordType();
2437  assert(Rec && "Invalid CFConstantStringType");
2438  CFConstantStringTypeDecl = Rec->getDecl();
2439}
2440
2441QualType ASTContext::getObjCFastEnumerationStateType()
2442{
2443  if (!ObjCFastEnumerationStateTypeDecl) {
2444    ObjCFastEnumerationStateTypeDecl =
2445      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2446                         &Idents.get("__objcFastEnumerationState"));
2447
2448    QualType FieldTypes[] = {
2449      UnsignedLongTy,
2450      getPointerType(ObjCIdType),
2451      getPointerType(UnsignedLongTy),
2452      getConstantArrayType(UnsignedLongTy,
2453                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2454    };
2455
2456    for (size_t i = 0; i < 4; ++i) {
2457      FieldDecl *Field = FieldDecl::Create(*this,
2458                                           ObjCFastEnumerationStateTypeDecl,
2459                                           SourceLocation(), 0,
2460                                           FieldTypes[i], /*BitWidth=*/0,
2461                                           /*Mutable=*/false);
2462      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
2463    }
2464
2465    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
2466  }
2467
2468  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2469}
2470
2471void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2472  const RecordType *Rec = T->getAsRecordType();
2473  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2474  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2475}
2476
2477// This returns true if a type has been typedefed to BOOL:
2478// typedef <type> BOOL;
2479static bool isTypeTypedefedAsBOOL(QualType T) {
2480  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
2481    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2482      return II->isStr("BOOL");
2483
2484  return false;
2485}
2486
2487/// getObjCEncodingTypeSize returns size of type for objective-c encoding
2488/// purpose.
2489int ASTContext::getObjCEncodingTypeSize(QualType type) {
2490  uint64_t sz = getTypeSize(type);
2491
2492  // Make all integer and enum types at least as large as an int
2493  if (sz > 0 && type->isIntegralType())
2494    sz = std::max(sz, getTypeSize(IntTy));
2495  // Treat arrays as pointers, since that's how they're passed in.
2496  else if (type->isArrayType())
2497    sz = getTypeSize(VoidPtrTy);
2498  return sz / getTypeSize(CharTy);
2499}
2500
2501/// getObjCEncodingForMethodDecl - Return the encoded type for this method
2502/// declaration.
2503void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
2504                                              std::string& S) {
2505  // FIXME: This is not very efficient.
2506  // Encode type qualifer, 'in', 'inout', etc. for the return type.
2507  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
2508  // Encode result type.
2509  getObjCEncodingForType(Decl->getResultType(), S);
2510  // Compute size of all parameters.
2511  // Start with computing size of a pointer in number of bytes.
2512  // FIXME: There might(should) be a better way of doing this computation!
2513  SourceLocation Loc;
2514  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
2515  // The first two arguments (self and _cmd) are pointers; account for
2516  // their size.
2517  int ParmOffset = 2 * PtrSize;
2518  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2519       E = Decl->param_end(); PI != E; ++PI) {
2520    QualType PType = (*PI)->getType();
2521    int sz = getObjCEncodingTypeSize(PType);
2522    assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
2523    ParmOffset += sz;
2524  }
2525  S += llvm::utostr(ParmOffset);
2526  S += "@0:";
2527  S += llvm::utostr(PtrSize);
2528
2529  // Argument types.
2530  ParmOffset = 2 * PtrSize;
2531  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2532       E = Decl->param_end(); PI != E; ++PI) {
2533    ParmVarDecl *PVDecl = *PI;
2534    QualType PType = PVDecl->getOriginalType();
2535    if (const ArrayType *AT =
2536          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2537      // Use array's original type only if it has known number of
2538      // elements.
2539      if (!isa<ConstantArrayType>(AT))
2540        PType = PVDecl->getType();
2541    } else if (PType->isFunctionType())
2542      PType = PVDecl->getType();
2543    // Process argument qualifiers for user supplied arguments; such as,
2544    // 'in', 'inout', etc.
2545    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
2546    getObjCEncodingForType(PType, S);
2547    S += llvm::utostr(ParmOffset);
2548    ParmOffset += getObjCEncodingTypeSize(PType);
2549  }
2550}
2551
2552/// getObjCEncodingForPropertyDecl - Return the encoded type for this
2553/// property declaration. If non-NULL, Container must be either an
2554/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2555/// NULL when getting encodings for protocol properties.
2556/// Property attributes are stored as a comma-delimited C string. The simple
2557/// attributes readonly and bycopy are encoded as single characters. The
2558/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2559/// encoded as single characters, followed by an identifier. Property types
2560/// are also encoded as a parametrized attribute. The characters used to encode
2561/// these attributes are defined by the following enumeration:
2562/// @code
2563/// enum PropertyAttributes {
2564/// kPropertyReadOnly = 'R',   // property is read-only.
2565/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
2566/// kPropertyByref = '&',  // property is a reference to the value last assigned
2567/// kPropertyDynamic = 'D',    // property is dynamic
2568/// kPropertyGetter = 'G',     // followed by getter selector name
2569/// kPropertySetter = 'S',     // followed by setter selector name
2570/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
2571/// kPropertyType = 't'              // followed by old-style type encoding.
2572/// kPropertyWeak = 'W'              // 'weak' property
2573/// kPropertyStrong = 'P'            // property GC'able
2574/// kPropertyNonAtomic = 'N'         // property non-atomic
2575/// };
2576/// @endcode
2577void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2578                                                const Decl *Container,
2579                                                std::string& S) {
2580  // Collect information from the property implementation decl(s).
2581  bool Dynamic = false;
2582  ObjCPropertyImplDecl *SynthesizePID = 0;
2583
2584  // FIXME: Duplicated code due to poor abstraction.
2585  if (Container) {
2586    if (const ObjCCategoryImplDecl *CID =
2587        dyn_cast<ObjCCategoryImplDecl>(Container)) {
2588      for (ObjCCategoryImplDecl::propimpl_iterator
2589             i = CID->propimpl_begin(), e = CID->propimpl_end();
2590           i != e; ++i) {
2591        ObjCPropertyImplDecl *PID = *i;
2592        if (PID->getPropertyDecl() == PD) {
2593          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2594            Dynamic = true;
2595          } else {
2596            SynthesizePID = PID;
2597          }
2598        }
2599      }
2600    } else {
2601      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
2602      for (ObjCCategoryImplDecl::propimpl_iterator
2603             i = OID->propimpl_begin(), e = OID->propimpl_end();
2604           i != e; ++i) {
2605        ObjCPropertyImplDecl *PID = *i;
2606        if (PID->getPropertyDecl() == PD) {
2607          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2608            Dynamic = true;
2609          } else {
2610            SynthesizePID = PID;
2611          }
2612        }
2613      }
2614    }
2615  }
2616
2617  // FIXME: This is not very efficient.
2618  S = "T";
2619
2620  // Encode result type.
2621  // GCC has some special rules regarding encoding of properties which
2622  // closely resembles encoding of ivars.
2623  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
2624                             true /* outermost type */,
2625                             true /* encoding for property */);
2626
2627  if (PD->isReadOnly()) {
2628    S += ",R";
2629  } else {
2630    switch (PD->getSetterKind()) {
2631    case ObjCPropertyDecl::Assign: break;
2632    case ObjCPropertyDecl::Copy:   S += ",C"; break;
2633    case ObjCPropertyDecl::Retain: S += ",&"; break;
2634    }
2635  }
2636
2637  // It really isn't clear at all what this means, since properties
2638  // are "dynamic by default".
2639  if (Dynamic)
2640    S += ",D";
2641
2642  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2643    S += ",N";
2644
2645  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2646    S += ",G";
2647    S += PD->getGetterName().getAsString();
2648  }
2649
2650  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2651    S += ",S";
2652    S += PD->getSetterName().getAsString();
2653  }
2654
2655  if (SynthesizePID) {
2656    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2657    S += ",V";
2658    S += OID->getNameAsString();
2659  }
2660
2661  // FIXME: OBJCGC: weak & strong
2662}
2663
2664/// getLegacyIntegralTypeEncoding -
2665/// Another legacy compatibility encoding: 32-bit longs are encoded as
2666/// 'l' or 'L' , but not always.  For typedefs, we need to use
2667/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2668///
2669void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2670  if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2671    if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
2672      if (BT->getKind() == BuiltinType::ULong &&
2673          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2674        PointeeTy = UnsignedIntTy;
2675      else
2676        if (BT->getKind() == BuiltinType::Long &&
2677            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2678          PointeeTy = IntTy;
2679    }
2680  }
2681}
2682
2683void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
2684                                        const FieldDecl *Field) {
2685  // We follow the behavior of gcc, expanding structures which are
2686  // directly pointed to, and expanding embedded structures. Note that
2687  // these rules are sufficient to prevent recursive encoding of the
2688  // same type.
2689  getObjCEncodingForTypeImpl(T, S, true, true, Field,
2690                             true /* outermost type */);
2691}
2692
2693static void EncodeBitField(const ASTContext *Context, std::string& S,
2694                           const FieldDecl *FD) {
2695  const Expr *E = FD->getBitWidth();
2696  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2697  ASTContext *Ctx = const_cast<ASTContext*>(Context);
2698  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
2699  S += 'b';
2700  S += llvm::utostr(N);
2701}
2702
2703void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2704                                            bool ExpandPointedToStructures,
2705                                            bool ExpandStructures,
2706                                            const FieldDecl *FD,
2707                                            bool OutermostType,
2708                                            bool EncodingProperty) {
2709  if (const BuiltinType *BT = T->getAsBuiltinType()) {
2710    if (FD && FD->isBitField()) {
2711      EncodeBitField(this, S, FD);
2712    }
2713    else {
2714      char encoding;
2715      switch (BT->getKind()) {
2716      default: assert(0 && "Unhandled builtin type kind");
2717      case BuiltinType::Void:       encoding = 'v'; break;
2718      case BuiltinType::Bool:       encoding = 'B'; break;
2719      case BuiltinType::Char_U:
2720      case BuiltinType::UChar:      encoding = 'C'; break;
2721      case BuiltinType::UShort:     encoding = 'S'; break;
2722      case BuiltinType::UInt:       encoding = 'I'; break;
2723      case BuiltinType::ULong:
2724          encoding =
2725            (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2726          break;
2727      case BuiltinType::UInt128:    encoding = 'T'; break;
2728      case BuiltinType::ULongLong:  encoding = 'Q'; break;
2729      case BuiltinType::Char_S:
2730      case BuiltinType::SChar:      encoding = 'c'; break;
2731      case BuiltinType::Short:      encoding = 's'; break;
2732      case BuiltinType::Int:        encoding = 'i'; break;
2733      case BuiltinType::Long:
2734        encoding =
2735          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2736        break;
2737      case BuiltinType::LongLong:   encoding = 'q'; break;
2738      case BuiltinType::Int128:     encoding = 't'; break;
2739      case BuiltinType::Float:      encoding = 'f'; break;
2740      case BuiltinType::Double:     encoding = 'd'; break;
2741      case BuiltinType::LongDouble: encoding = 'd'; break;
2742      }
2743
2744      S += encoding;
2745    }
2746  } else if (const ComplexType *CT = T->getAsComplexType()) {
2747    S += 'j';
2748    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2749                               false);
2750  }
2751  else if (const PointerType *PT = T->getAsPointerType()) {
2752    QualType PointeeTy = PT->getPointeeType();
2753    bool isReadOnly = false;
2754    // For historical/compatibility reasons, the read-only qualifier of the
2755    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
2756    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2757    // Also, do not emit the 'r' for anything but the outermost type!
2758    if (dyn_cast<TypedefType>(T.getTypePtr())) {
2759      if (OutermostType && T.isConstQualified()) {
2760        isReadOnly = true;
2761        S += 'r';
2762      }
2763    }
2764    else if (OutermostType) {
2765      QualType P = PointeeTy;
2766      while (P->getAsPointerType())
2767        P = P->getAsPointerType()->getPointeeType();
2768      if (P.isConstQualified()) {
2769        isReadOnly = true;
2770        S += 'r';
2771      }
2772    }
2773    if (isReadOnly) {
2774      // Another legacy compatibility encoding. Some ObjC qualifier and type
2775      // combinations need to be rearranged.
2776      // Rewrite "in const" from "nr" to "rn"
2777      const char * s = S.c_str();
2778      int len = S.length();
2779      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2780        std::string replace = "rn";
2781        S.replace(S.end()-2, S.end(), replace);
2782      }
2783    }
2784    if (isObjCSelType(PointeeTy)) {
2785      S += ':';
2786      return;
2787    }
2788
2789    if (PointeeTy->isCharType()) {
2790      // char pointer types should be encoded as '*' unless it is a
2791      // type that has been typedef'd to 'BOOL'.
2792      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
2793        S += '*';
2794        return;
2795      }
2796    }
2797
2798    S += '^';
2799    getLegacyIntegralTypeEncoding(PointeeTy);
2800
2801    getObjCEncodingForTypeImpl(PointeeTy, S,
2802                               false, ExpandPointedToStructures,
2803                               NULL);
2804  } else if (const ArrayType *AT =
2805               // Ignore type qualifiers etc.
2806               dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
2807    if (isa<IncompleteArrayType>(AT)) {
2808      // Incomplete arrays are encoded as a pointer to the array element.
2809      S += '^';
2810
2811      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2812                                 false, ExpandStructures, FD);
2813    } else {
2814      S += '[';
2815
2816      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2817        S += llvm::utostr(CAT->getSize().getZExtValue());
2818      else {
2819        //Variable length arrays are encoded as a regular array with 0 elements.
2820        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2821        S += '0';
2822      }
2823
2824      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2825                                 false, ExpandStructures, FD);
2826      S += ']';
2827    }
2828  } else if (T->getAsFunctionType()) {
2829    S += '?';
2830  } else if (const RecordType *RTy = T->getAsRecordType()) {
2831    RecordDecl *RDecl = RTy->getDecl();
2832    S += RDecl->isUnion() ? '(' : '{';
2833    // Anonymous structures print as '?'
2834    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2835      S += II->getName();
2836    } else {
2837      S += '?';
2838    }
2839    if (ExpandStructures) {
2840      S += '=';
2841      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2842                                   FieldEnd = RDecl->field_end();
2843           Field != FieldEnd; ++Field) {
2844        if (FD) {
2845          S += '"';
2846          S += Field->getNameAsString();
2847          S += '"';
2848        }
2849
2850        // Special case bit-fields.
2851        if (Field->isBitField()) {
2852          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2853                                     (*Field));
2854        } else {
2855          QualType qt = Field->getType();
2856          getLegacyIntegralTypeEncoding(qt);
2857          getObjCEncodingForTypeImpl(qt, S, false, true,
2858                                     FD);
2859        }
2860      }
2861    }
2862    S += RDecl->isUnion() ? ')' : '}';
2863  } else if (T->isEnumeralType()) {
2864    if (FD && FD->isBitField())
2865      EncodeBitField(this, S, FD);
2866    else
2867      S += 'i';
2868  } else if (T->isBlockPointerType()) {
2869    S += "@?"; // Unlike a pointer-to-function, which is "^?".
2870  } else if (T->isObjCInterfaceType()) {
2871    // @encode(class_name)
2872    ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2873    S += '{';
2874    const IdentifierInfo *II = OI->getIdentifier();
2875    S += II->getName();
2876    S += '=';
2877    llvm::SmallVector<FieldDecl*, 32> RecFields;
2878    CollectObjCIvars(OI, RecFields);
2879    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2880      if (RecFields[i]->isBitField())
2881        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2882                                   RecFields[i]);
2883      else
2884        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2885                                   FD);
2886    }
2887    S += '}';
2888  }
2889  else if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
2890    if (OPT->isObjCIdType()) {
2891      S += '@';
2892      return;
2893    } else if (OPT->isObjCClassType()) {
2894      S += '#';
2895      return;
2896    } else if (OPT->isObjCQualifiedIdType()) {
2897      getObjCEncodingForTypeImpl(getObjCIdType(), S,
2898                                 ExpandPointedToStructures,
2899                                 ExpandStructures, FD);
2900      if (FD || EncodingProperty) {
2901        // Note that we do extended encoding of protocol qualifer list
2902        // Only when doing ivar or property encoding.
2903        const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
2904        S += '"';
2905        for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
2906             E = QIDT->qual_end(); I != E; ++I) {
2907          S += '<';
2908          S += (*I)->getNameAsString();
2909          S += '>';
2910        }
2911        S += '"';
2912      }
2913      return;
2914    } else {
2915      QualType PointeeTy = OPT->getPointeeType();
2916      if (!EncodingProperty &&
2917          isa<TypedefType>(PointeeTy.getTypePtr())) {
2918        // Another historical/compatibility reason.
2919        // We encode the underlying type which comes out as
2920        // {...};
2921        S += '^';
2922        getObjCEncodingForTypeImpl(PointeeTy, S,
2923                                   false, ExpandPointedToStructures,
2924                                   NULL);
2925        return;
2926      }
2927      S += '@';
2928      if (FD || EncodingProperty) {
2929        const ObjCInterfaceType *OIT = OPT->getInterfaceType();
2930        ObjCInterfaceDecl *OI = OIT->getDecl();
2931        S += '"';
2932        S += OI->getNameAsCString();
2933        for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2934             E = OIT->qual_end(); I != E; ++I) {
2935          S += '<';
2936          S += (*I)->getNameAsString();
2937          S += '>';
2938        }
2939        S += '"';
2940      }
2941      return;
2942    }
2943  } else
2944    assert(0 && "@encode for type not implemented!");
2945}
2946
2947void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
2948                                                 std::string& S) const {
2949  if (QT & Decl::OBJC_TQ_In)
2950    S += 'n';
2951  if (QT & Decl::OBJC_TQ_Inout)
2952    S += 'N';
2953  if (QT & Decl::OBJC_TQ_Out)
2954    S += 'o';
2955  if (QT & Decl::OBJC_TQ_Bycopy)
2956    S += 'O';
2957  if (QT & Decl::OBJC_TQ_Byref)
2958    S += 'R';
2959  if (QT & Decl::OBJC_TQ_Oneway)
2960    S += 'V';
2961}
2962
2963void ASTContext::setBuiltinVaListType(QualType T)
2964{
2965  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2966
2967  BuiltinVaListType = T;
2968}
2969
2970void ASTContext::setObjCIdType(QualType T)
2971{
2972  ObjCIdType = T;
2973  const TypedefType *TT = T->getAsTypedefType();
2974  assert(TT && "missing 'id' typedef");
2975  const ObjCObjectPointerType *OPT =
2976    TT->getDecl()->getUnderlyingType()->getAsObjCObjectPointerType();
2977  assert(OPT && "missing 'id' type");
2978  ObjCObjectPointerType::setIdInterface(OPT->getPointeeType());
2979}
2980
2981void ASTContext::setObjCSelType(QualType T)
2982{
2983  ObjCSelType = T;
2984
2985  const TypedefType *TT = T->getAsTypedefType();
2986  if (!TT)
2987    return;
2988  TypedefDecl *TD = TT->getDecl();
2989
2990  // typedef struct objc_selector *SEL;
2991  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2992  if (!ptr)
2993    return;
2994  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2995  if (!rec)
2996    return;
2997  SelStructType = rec;
2998}
2999
3000void ASTContext::setObjCProtoType(QualType QT)
3001{
3002  ObjCProtoType = QT;
3003}
3004
3005void ASTContext::setObjCClassType(QualType T)
3006{
3007  ObjCClassType = T;
3008  const TypedefType *TT = T->getAsTypedefType();
3009  assert(TT && "missing 'Class' typedef");
3010  const ObjCObjectPointerType *OPT =
3011    TT->getDecl()->getUnderlyingType()->getAsObjCObjectPointerType();
3012  assert(OPT && "missing 'Class' type");
3013  ObjCObjectPointerType::setClassInterface(OPT->getPointeeType());
3014}
3015
3016void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3017  assert(ObjCConstantStringType.isNull() &&
3018         "'NSConstantString' type already set!");
3019
3020  ObjCConstantStringType = getObjCInterfaceType(Decl);
3021}
3022
3023/// \brief Retrieve the template name that represents a qualified
3024/// template name such as \c std::vector.
3025TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3026                                                  bool TemplateKeyword,
3027                                                  TemplateDecl *Template) {
3028  llvm::FoldingSetNodeID ID;
3029  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3030
3031  void *InsertPos = 0;
3032  QualifiedTemplateName *QTN =
3033    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3034  if (!QTN) {
3035    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3036    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3037  }
3038
3039  return TemplateName(QTN);
3040}
3041
3042/// \brief Retrieve the template name that represents a dependent
3043/// template name such as \c MetaFun::template apply.
3044TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3045                                                  const IdentifierInfo *Name) {
3046  assert(NNS->isDependent() && "Nested name specifier must be dependent");
3047
3048  llvm::FoldingSetNodeID ID;
3049  DependentTemplateName::Profile(ID, NNS, Name);
3050
3051  void *InsertPos = 0;
3052  DependentTemplateName *QTN =
3053    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3054
3055  if (QTN)
3056    return TemplateName(QTN);
3057
3058  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3059  if (CanonNNS == NNS) {
3060    QTN = new (*this,4) DependentTemplateName(NNS, Name);
3061  } else {
3062    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3063    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3064  }
3065
3066  DependentTemplateNames.InsertNode(QTN, InsertPos);
3067  return TemplateName(QTN);
3068}
3069
3070/// getFromTargetType - Given one of the integer types provided by
3071/// TargetInfo, produce the corresponding type. The unsigned @p Type
3072/// is actually a value of type @c TargetInfo::IntType.
3073QualType ASTContext::getFromTargetType(unsigned Type) const {
3074  switch (Type) {
3075  case TargetInfo::NoInt: return QualType();
3076  case TargetInfo::SignedShort: return ShortTy;
3077  case TargetInfo::UnsignedShort: return UnsignedShortTy;
3078  case TargetInfo::SignedInt: return IntTy;
3079  case TargetInfo::UnsignedInt: return UnsignedIntTy;
3080  case TargetInfo::SignedLong: return LongTy;
3081  case TargetInfo::UnsignedLong: return UnsignedLongTy;
3082  case TargetInfo::SignedLongLong: return LongLongTy;
3083  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3084  }
3085
3086  assert(false && "Unhandled TargetInfo::IntType value");
3087  return QualType();
3088}
3089
3090//===----------------------------------------------------------------------===//
3091//                        Type Predicates.
3092//===----------------------------------------------------------------------===//
3093
3094/// isObjCNSObjectType - Return true if this is an NSObject object using
3095/// NSObject attribute on a c-style pointer type.
3096/// FIXME - Make it work directly on types.
3097///
3098bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3099  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3100    if (TypedefDecl *TD = TDT->getDecl())
3101      if (TD->getAttr<ObjCNSObjectAttr>())
3102        return true;
3103  }
3104  return false;
3105}
3106
3107/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
3108/// to an object type.  This includes "id" and "Class" (two 'special' pointers
3109/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
3110/// ID type).
3111bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
3112  if (Ty->isObjCObjectPointerType())
3113    return true;
3114  if (Ty->isObjCQualifiedIdType())
3115    return true;
3116
3117  // Blocks are objects.
3118  if (Ty->isBlockPointerType())
3119    return true;
3120
3121  // All other object types are pointers.
3122  const PointerType *PT = Ty->getAsPointerType();
3123  if (PT == 0)
3124    return false;
3125
3126  // If this a pointer to an interface (e.g. NSString*), it is ok.
3127  if (PT->getPointeeType()->isObjCInterfaceType() ||
3128      // If is has NSObject attribute, OK as well.
3129      isObjCNSObjectType(Ty))
3130    return true;
3131
3132  // Check to see if this is 'id' or 'Class', both of which are typedefs for
3133  // pointer types.  This looks for the typedef specifically, not for the
3134  // underlying type.  Iteratively strip off typedefs so that we can handle
3135  // typedefs of typedefs.
3136  while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3137    if (Ty.getUnqualifiedType() == getObjCIdType() ||
3138        Ty.getUnqualifiedType() == getObjCClassType())
3139      return true;
3140
3141    Ty = TDT->getDecl()->getUnderlyingType();
3142  }
3143
3144  return false;
3145}
3146
3147/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3148/// garbage collection attribute.
3149///
3150QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3151  QualType::GCAttrTypes GCAttrs = QualType::GCNone;
3152  if (getLangOptions().ObjC1 &&
3153      getLangOptions().getGCMode() != LangOptions::NonGC) {
3154    GCAttrs = Ty.getObjCGCAttr();
3155    // Default behavious under objective-c's gc is for objective-c pointers
3156    // (or pointers to them) be treated as though they were declared
3157    // as __strong.
3158    if (GCAttrs == QualType::GCNone) {
3159      if (isObjCObjectPointerType(Ty))
3160        GCAttrs = QualType::Strong;
3161      else if (Ty->isPointerType())
3162        return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
3163    }
3164    // Non-pointers have none gc'able attribute regardless of the attribute
3165    // set on them.
3166    else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
3167      return QualType::GCNone;
3168  }
3169  return GCAttrs;
3170}
3171
3172//===----------------------------------------------------------------------===//
3173//                        Type Compatibility Testing
3174//===----------------------------------------------------------------------===//
3175
3176/// areCompatVectorTypes - Return true if the two specified vector types are
3177/// compatible.
3178static bool areCompatVectorTypes(const VectorType *LHS,
3179                                 const VectorType *RHS) {
3180  assert(LHS->isCanonical() && RHS->isCanonical());
3181  return LHS->getElementType() == RHS->getElementType() &&
3182         LHS->getNumElements() == RHS->getNumElements();
3183}
3184
3185/// canAssignObjCInterfaces - Return true if the two interface types are
3186/// compatible for assignment from RHS to LHS.  This handles validation of any
3187/// protocol qualifiers on the LHS or RHS.
3188///
3189/// FIXME: Move the following to ObjCObjectPointerType/ObjCInterfaceType.
3190bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3191                                         const ObjCObjectPointerType *RHSOPT) {
3192  // If either interface represents the built-in 'id' or 'Class' types,
3193  // then return true (no need to call canAssignObjCInterfaces()).
3194  if (LHSOPT->isObjCIdType() || RHSOPT->isObjCIdType() ||
3195      LHSOPT->isObjCClassType() || RHSOPT->isObjCClassType())
3196    return true;
3197
3198  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3199  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
3200  if (!LHS || !RHS)
3201    return false;
3202  return canAssignObjCInterfaces(LHS, RHS);
3203}
3204
3205bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3206                                         const ObjCInterfaceType *RHS) {
3207  // If either interface represents the built-in 'id' or 'Class' types,
3208  // then return true.
3209  if (LHS->isObjCIdInterface() || RHS->isObjCIdInterface() ||
3210      LHS->isObjCClassInterface() || RHS->isObjCClassInterface())
3211    return true;
3212
3213  // Verify that the base decls are compatible: the RHS must be a subclass of
3214  // the LHS.
3215  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3216    return false;
3217
3218  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
3219  // protocol qualified at all, then we are good.
3220  if (!isa<ObjCQualifiedInterfaceType>(LHS))
3221    return true;
3222
3223  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
3224  // isn't a superset.
3225  if (!isa<ObjCQualifiedInterfaceType>(RHS))
3226    return true;  // FIXME: should return false!
3227
3228  // Finally, we must have two protocol-qualified interfaces.
3229  const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
3230  const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
3231
3232  // All LHS protocols must have a presence on the RHS.
3233  assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
3234
3235  for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
3236                                                 LHSPE = LHSP->qual_end();
3237       LHSPI != LHSPE; LHSPI++) {
3238    bool RHSImplementsProtocol = false;
3239
3240    // If the RHS doesn't implement the protocol on the left, the types
3241    // are incompatible.
3242    for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
3243                                                   RHSPE = RHSP->qual_end();
3244         !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
3245      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
3246        RHSImplementsProtocol = true;
3247    }
3248    // FIXME: For better diagnostics, consider passing back the protocol name.
3249    if (!RHSImplementsProtocol)
3250      return false;
3251  }
3252  // The RHS implements all protocols listed on the LHS.
3253  return true;
3254}
3255
3256bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3257  // get the "pointed to" types
3258  const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3259  const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
3260
3261  if (!LHSOPT || !RHSOPT)
3262    return false;
3263
3264  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3265         canAssignObjCInterfaces(RHSOPT, LHSOPT);
3266}
3267
3268/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3269/// both shall have the identically qualified version of a compatible type.
3270/// C99 6.2.7p1: Two types have compatible types if their types are the
3271/// same. See 6.7.[2,3,5] for additional rules.
3272bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3273  return !mergeTypes(LHS, RHS).isNull();
3274}
3275
3276QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3277  const FunctionType *lbase = lhs->getAsFunctionType();
3278  const FunctionType *rbase = rhs->getAsFunctionType();
3279  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3280  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
3281  bool allLTypes = true;
3282  bool allRTypes = true;
3283
3284  // Check return type
3285  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3286  if (retType.isNull()) return QualType();
3287  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3288    allLTypes = false;
3289  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3290    allRTypes = false;
3291
3292  if (lproto && rproto) { // two C99 style function prototypes
3293    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3294           "C++ shouldn't be here");
3295    unsigned lproto_nargs = lproto->getNumArgs();
3296    unsigned rproto_nargs = rproto->getNumArgs();
3297
3298    // Compatible functions must have the same number of arguments
3299    if (lproto_nargs != rproto_nargs)
3300      return QualType();
3301
3302    // Variadic and non-variadic functions aren't compatible
3303    if (lproto->isVariadic() != rproto->isVariadic())
3304      return QualType();
3305
3306    if (lproto->getTypeQuals() != rproto->getTypeQuals())
3307      return QualType();
3308
3309    // Check argument compatibility
3310    llvm::SmallVector<QualType, 10> types;
3311    for (unsigned i = 0; i < lproto_nargs; i++) {
3312      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3313      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3314      QualType argtype = mergeTypes(largtype, rargtype);
3315      if (argtype.isNull()) return QualType();
3316      types.push_back(argtype);
3317      if (getCanonicalType(argtype) != getCanonicalType(largtype))
3318        allLTypes = false;
3319      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3320        allRTypes = false;
3321    }
3322    if (allLTypes) return lhs;
3323    if (allRTypes) return rhs;
3324    return getFunctionType(retType, types.begin(), types.size(),
3325                           lproto->isVariadic(), lproto->getTypeQuals());
3326  }
3327
3328  if (lproto) allRTypes = false;
3329  if (rproto) allLTypes = false;
3330
3331  const FunctionProtoType *proto = lproto ? lproto : rproto;
3332  if (proto) {
3333    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
3334    if (proto->isVariadic()) return QualType();
3335    // Check that the types are compatible with the types that
3336    // would result from default argument promotions (C99 6.7.5.3p15).
3337    // The only types actually affected are promotable integer
3338    // types and floats, which would be passed as a different
3339    // type depending on whether the prototype is visible.
3340    unsigned proto_nargs = proto->getNumArgs();
3341    for (unsigned i = 0; i < proto_nargs; ++i) {
3342      QualType argTy = proto->getArgType(i);
3343      if (argTy->isPromotableIntegerType() ||
3344          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3345        return QualType();
3346    }
3347
3348    if (allLTypes) return lhs;
3349    if (allRTypes) return rhs;
3350    return getFunctionType(retType, proto->arg_type_begin(),
3351                           proto->getNumArgs(), lproto->isVariadic(),
3352                           lproto->getTypeQuals());
3353  }
3354
3355  if (allLTypes) return lhs;
3356  if (allRTypes) return rhs;
3357  return getFunctionNoProtoType(retType);
3358}
3359
3360QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
3361  // C++ [expr]: If an expression initially has the type "reference to T", the
3362  // type is adjusted to "T" prior to any further analysis, the expression
3363  // designates the object or function denoted by the reference, and the
3364  // expression is an lvalue unless the reference is an rvalue reference and
3365  // the expression is a function call (possibly inside parentheses).
3366  // FIXME: C++ shouldn't be going through here!  The rules are different
3367  // enough that they should be handled separately.
3368  // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3369  // shouldn't be going through here!
3370  if (const ReferenceType *RT = LHS->getAsReferenceType())
3371    LHS = RT->getPointeeType();
3372  if (const ReferenceType *RT = RHS->getAsReferenceType())
3373    RHS = RT->getPointeeType();
3374
3375  QualType LHSCan = getCanonicalType(LHS),
3376           RHSCan = getCanonicalType(RHS);
3377
3378  // If two types are identical, they are compatible.
3379  if (LHSCan == RHSCan)
3380    return LHS;
3381
3382  // If the qualifiers are different, the types aren't compatible
3383  // Note that we handle extended qualifiers later, in the
3384  // case for ExtQualType.
3385  if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
3386    return QualType();
3387
3388  Type::TypeClass LHSClass = LHSCan->getTypeClass();
3389  Type::TypeClass RHSClass = RHSCan->getTypeClass();
3390
3391  // We want to consider the two function types to be the same for these
3392  // comparisons, just force one to the other.
3393  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3394  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
3395
3396  // Strip off objc_gc attributes off the top level so they can be merged.
3397  // This is a complete mess, but the attribute itself doesn't make much sense.
3398  if (RHSClass == Type::ExtQual) {
3399    QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3400    if (GCAttr != QualType::GCNone) {
3401      QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
3402      // __weak attribute must appear on both declarations.
3403      // __strong attribue is redundant if other decl is an objective-c
3404      // object pointer (or decorated with __strong attribute); otherwise
3405      // issue error.
3406      if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3407          (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3408           !LHSCan->isObjCObjectPointerType()))
3409        return QualType();
3410
3411      RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3412                     RHS.getCVRQualifiers());
3413      QualType Result = mergeTypes(LHS, RHS);
3414      if (!Result.isNull()) {
3415        if (Result.getObjCGCAttr() == QualType::GCNone)
3416          Result = getObjCGCQualType(Result, GCAttr);
3417        else if (Result.getObjCGCAttr() != GCAttr)
3418          Result = QualType();
3419      }
3420      return Result;
3421    }
3422  }
3423  if (LHSClass == Type::ExtQual) {
3424    QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3425    if (GCAttr != QualType::GCNone) {
3426      QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3427      // __weak attribute must appear on both declarations. __strong
3428      // __strong attribue is redundant if other decl is an objective-c
3429      // object pointer (or decorated with __strong attribute); otherwise
3430      // issue error.
3431      if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3432          (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3433           !RHSCan->isObjCObjectPointerType()))
3434        return QualType();
3435
3436      LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3437                     LHS.getCVRQualifiers());
3438      QualType Result = mergeTypes(LHS, RHS);
3439      if (!Result.isNull()) {
3440        if (Result.getObjCGCAttr() == QualType::GCNone)
3441          Result = getObjCGCQualType(Result, GCAttr);
3442        else if (Result.getObjCGCAttr() != GCAttr)
3443          Result = QualType();
3444      }
3445      return Result;
3446    }
3447  }
3448
3449  // Same as above for arrays
3450  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3451    LHSClass = Type::ConstantArray;
3452  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3453    RHSClass = Type::ConstantArray;
3454
3455  // Canonicalize ExtVector -> Vector.
3456  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3457  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
3458
3459  // Consider qualified interfaces and interfaces the same.
3460  // FIXME: Remove (ObjCObjectPointerType should obsolete this funny business).
3461  if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3462  if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
3463
3464  // If the canonical type classes don't match.
3465  if (LHSClass != RHSClass) {
3466    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3467    // a signed integer type, or an unsigned integer type.
3468    if (const EnumType* ETy = LHS->getAsEnumType()) {
3469      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3470        return RHS;
3471    }
3472    if (const EnumType* ETy = RHS->getAsEnumType()) {
3473      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3474        return LHS;
3475    }
3476
3477    return QualType();
3478  }
3479
3480  // The canonical type classes match.
3481  switch (LHSClass) {
3482#define TYPE(Class, Base)
3483#define ABSTRACT_TYPE(Class, Base)
3484#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3485#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3486#include "clang/AST/TypeNodes.def"
3487    assert(false && "Non-canonical and dependent types shouldn't get here");
3488    return QualType();
3489
3490  case Type::LValueReference:
3491  case Type::RValueReference:
3492  case Type::MemberPointer:
3493    assert(false && "C++ should never be in mergeTypes");
3494    return QualType();
3495
3496  case Type::IncompleteArray:
3497  case Type::VariableArray:
3498  case Type::FunctionProto:
3499  case Type::ExtVector:
3500  case Type::ObjCQualifiedInterface:
3501    assert(false && "Types are eliminated above");
3502    return QualType();
3503
3504  case Type::Pointer:
3505  {
3506    // Merge two pointer types, while trying to preserve typedef info
3507    QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3508    QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3509    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3510    if (ResultType.isNull()) return QualType();
3511    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3512      return LHS;
3513    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3514      return RHS;
3515    return getPointerType(ResultType);
3516  }
3517  case Type::BlockPointer:
3518  {
3519    // Merge two block pointer types, while trying to preserve typedef info
3520    QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3521    QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3522    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3523    if (ResultType.isNull()) return QualType();
3524    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3525      return LHS;
3526    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3527      return RHS;
3528    return getBlockPointerType(ResultType);
3529  }
3530  case Type::ConstantArray:
3531  {
3532    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3533    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3534    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3535      return QualType();
3536
3537    QualType LHSElem = getAsArrayType(LHS)->getElementType();
3538    QualType RHSElem = getAsArrayType(RHS)->getElementType();
3539    QualType ResultType = mergeTypes(LHSElem, RHSElem);
3540    if (ResultType.isNull()) return QualType();
3541    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3542      return LHS;
3543    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3544      return RHS;
3545    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3546                                          ArrayType::ArraySizeModifier(), 0);
3547    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3548                                          ArrayType::ArraySizeModifier(), 0);
3549    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3550    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
3551    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3552      return LHS;
3553    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3554      return RHS;
3555    if (LVAT) {
3556      // FIXME: This isn't correct! But tricky to implement because
3557      // the array's size has to be the size of LHS, but the type
3558      // has to be different.
3559      return LHS;
3560    }
3561    if (RVAT) {
3562      // FIXME: This isn't correct! But tricky to implement because
3563      // the array's size has to be the size of RHS, but the type
3564      // has to be different.
3565      return RHS;
3566    }
3567    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3568    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
3569    return getIncompleteArrayType(ResultType,
3570                                  ArrayType::ArraySizeModifier(), 0);
3571  }
3572  case Type::FunctionNoProto:
3573    return mergeFunctionTypes(LHS, RHS);
3574  case Type::Record:
3575  case Type::Enum:
3576    return QualType();
3577  case Type::Builtin:
3578    // Only exactly equal builtin types are compatible, which is tested above.
3579    return QualType();
3580  case Type::Complex:
3581    // Distinct complex types are incompatible.
3582    return QualType();
3583  case Type::Vector:
3584    // FIXME: The merged type should be an ExtVector!
3585    if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3586      return LHS;
3587    return QualType();
3588  case Type::ObjCInterface: {
3589    // Check if the interfaces are assignment compatible.
3590    // FIXME: This should be type compatibility, e.g. whether
3591    // "LHS x; RHS x;" at global scope is legal.
3592    const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3593    const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3594    if (LHSIface && RHSIface &&
3595        canAssignObjCInterfaces(LHSIface, RHSIface))
3596      return LHS;
3597
3598    return QualType();
3599  }
3600  case Type::ObjCObjectPointer: {
3601    // FIXME: Incorporate tests from Sema::ObjCQualifiedIdTypesAreCompatible().
3602    if (LHS->isObjCQualifiedIdType() && RHS->isObjCQualifiedIdType())
3603      return QualType();
3604
3605    if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3606                                RHS->getAsObjCObjectPointerType()))
3607      return LHS;
3608
3609    return QualType();
3610  }
3611  case Type::FixedWidthInt:
3612    // Distinct fixed-width integers are not compatible.
3613    return QualType();
3614  case Type::ExtQual:
3615    // FIXME: ExtQual types can be compatible even if they're not
3616    // identical!
3617    return QualType();
3618    // First attempt at an implementation, but I'm not really sure it's
3619    // right...
3620#if 0
3621    ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3622    ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3623    if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3624        LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3625      return QualType();
3626    QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3627    LHSBase = QualType(LQual->getBaseType(), 0);
3628    RHSBase = QualType(RQual->getBaseType(), 0);
3629    ResultType = mergeTypes(LHSBase, RHSBase);
3630    if (ResultType.isNull()) return QualType();
3631    ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3632    if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3633      return LHS;
3634    if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3635      return RHS;
3636    ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3637    ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3638    ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3639    return ResultType;
3640#endif
3641
3642  case Type::TemplateSpecialization:
3643    assert(false && "Dependent types have no size");
3644    break;
3645  }
3646
3647  return QualType();
3648}
3649
3650//===----------------------------------------------------------------------===//
3651//                         Integer Predicates
3652//===----------------------------------------------------------------------===//
3653
3654unsigned ASTContext::getIntWidth(QualType T) {
3655  if (T == BoolTy)
3656    return 1;
3657  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3658    return FWIT->getWidth();
3659  }
3660  // For builtin types, just use the standard type sizing method
3661  return (unsigned)getTypeSize(T);
3662}
3663
3664QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3665  assert(T->isSignedIntegerType() && "Unexpected type");
3666  if (const EnumType* ETy = T->getAsEnumType())
3667    T = ETy->getDecl()->getIntegerType();
3668  const BuiltinType* BTy = T->getAsBuiltinType();
3669  assert (BTy && "Unexpected signed integer type");
3670  switch (BTy->getKind()) {
3671  case BuiltinType::Char_S:
3672  case BuiltinType::SChar:
3673    return UnsignedCharTy;
3674  case BuiltinType::Short:
3675    return UnsignedShortTy;
3676  case BuiltinType::Int:
3677    return UnsignedIntTy;
3678  case BuiltinType::Long:
3679    return UnsignedLongTy;
3680  case BuiltinType::LongLong:
3681    return UnsignedLongLongTy;
3682  case BuiltinType::Int128:
3683    return UnsignedInt128Ty;
3684  default:
3685    assert(0 && "Unexpected signed integer type");
3686    return QualType();
3687  }
3688}
3689
3690ExternalASTSource::~ExternalASTSource() { }
3691
3692void ExternalASTSource::PrintStats() { }
3693
3694
3695//===----------------------------------------------------------------------===//
3696//                          Builtin Type Computation
3697//===----------------------------------------------------------------------===//
3698
3699/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3700/// pointer over the consumed characters.  This returns the resultant type.
3701static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3702                                  ASTContext::GetBuiltinTypeError &Error,
3703                                  bool AllowTypeModifiers = true) {
3704  // Modifiers.
3705  int HowLong = 0;
3706  bool Signed = false, Unsigned = false;
3707
3708  // Read the modifiers first.
3709  bool Done = false;
3710  while (!Done) {
3711    switch (*Str++) {
3712    default: Done = true; --Str; break;
3713    case 'S':
3714      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3715      assert(!Signed && "Can't use 'S' modifier multiple times!");
3716      Signed = true;
3717      break;
3718    case 'U':
3719      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3720      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3721      Unsigned = true;
3722      break;
3723    case 'L':
3724      assert(HowLong <= 2 && "Can't have LLLL modifier");
3725      ++HowLong;
3726      break;
3727    }
3728  }
3729
3730  QualType Type;
3731
3732  // Read the base type.
3733  switch (*Str++) {
3734  default: assert(0 && "Unknown builtin type letter!");
3735  case 'v':
3736    assert(HowLong == 0 && !Signed && !Unsigned &&
3737           "Bad modifiers used with 'v'!");
3738    Type = Context.VoidTy;
3739    break;
3740  case 'f':
3741    assert(HowLong == 0 && !Signed && !Unsigned &&
3742           "Bad modifiers used with 'f'!");
3743    Type = Context.FloatTy;
3744    break;
3745  case 'd':
3746    assert(HowLong < 2 && !Signed && !Unsigned &&
3747           "Bad modifiers used with 'd'!");
3748    if (HowLong)
3749      Type = Context.LongDoubleTy;
3750    else
3751      Type = Context.DoubleTy;
3752    break;
3753  case 's':
3754    assert(HowLong == 0 && "Bad modifiers used with 's'!");
3755    if (Unsigned)
3756      Type = Context.UnsignedShortTy;
3757    else
3758      Type = Context.ShortTy;
3759    break;
3760  case 'i':
3761    if (HowLong == 3)
3762      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3763    else if (HowLong == 2)
3764      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3765    else if (HowLong == 1)
3766      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3767    else
3768      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3769    break;
3770  case 'c':
3771    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3772    if (Signed)
3773      Type = Context.SignedCharTy;
3774    else if (Unsigned)
3775      Type = Context.UnsignedCharTy;
3776    else
3777      Type = Context.CharTy;
3778    break;
3779  case 'b': // boolean
3780    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3781    Type = Context.BoolTy;
3782    break;
3783  case 'z':  // size_t.
3784    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3785    Type = Context.getSizeType();
3786    break;
3787  case 'F':
3788    Type = Context.getCFConstantStringType();
3789    break;
3790  case 'a':
3791    Type = Context.getBuiltinVaListType();
3792    assert(!Type.isNull() && "builtin va list type not initialized!");
3793    break;
3794  case 'A':
3795    // This is a "reference" to a va_list; however, what exactly
3796    // this means depends on how va_list is defined. There are two
3797    // different kinds of va_list: ones passed by value, and ones
3798    // passed by reference.  An example of a by-value va_list is
3799    // x86, where va_list is a char*. An example of by-ref va_list
3800    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3801    // we want this argument to be a char*&; for x86-64, we want
3802    // it to be a __va_list_tag*.
3803    Type = Context.getBuiltinVaListType();
3804    assert(!Type.isNull() && "builtin va list type not initialized!");
3805    if (Type->isArrayType()) {
3806      Type = Context.getArrayDecayedType(Type);
3807    } else {
3808      Type = Context.getLValueReferenceType(Type);
3809    }
3810    break;
3811  case 'V': {
3812    char *End;
3813
3814    unsigned NumElements = strtoul(Str, &End, 10);
3815    assert(End != Str && "Missing vector size");
3816
3817    Str = End;
3818
3819    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3820    Type = Context.getVectorType(ElementType, NumElements);
3821    break;
3822  }
3823  case 'P': {
3824    Type = Context.getFILEType();
3825    if (Type.isNull()) {
3826      Error = ASTContext::GE_Missing_FILE;
3827      return QualType();
3828    } else {
3829      break;
3830    }
3831  }
3832  }
3833
3834  if (!AllowTypeModifiers)
3835    return Type;
3836
3837  Done = false;
3838  while (!Done) {
3839    switch (*Str++) {
3840      default: Done = true; --Str; break;
3841      case '*':
3842        Type = Context.getPointerType(Type);
3843        break;
3844      case '&':
3845        Type = Context.getLValueReferenceType(Type);
3846        break;
3847      // FIXME: There's no way to have a built-in with an rvalue ref arg.
3848      case 'C':
3849        Type = Type.getQualifiedType(QualType::Const);
3850        break;
3851    }
3852  }
3853
3854  return Type;
3855}
3856
3857/// GetBuiltinType - Return the type for the specified builtin.
3858QualType ASTContext::GetBuiltinType(unsigned id,
3859                                    GetBuiltinTypeError &Error) {
3860  const char *TypeStr = BuiltinInfo.GetTypeString(id);
3861
3862  llvm::SmallVector<QualType, 8> ArgTypes;
3863
3864  Error = GE_None;
3865  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3866  if (Error != GE_None)
3867    return QualType();
3868  while (TypeStr[0] && TypeStr[0] != '.') {
3869    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3870    if (Error != GE_None)
3871      return QualType();
3872
3873    // Do array -> pointer decay.  The builtin should use the decayed type.
3874    if (Ty->isArrayType())
3875      Ty = getArrayDecayedType(Ty);
3876
3877    ArgTypes.push_back(Ty);
3878  }
3879
3880  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3881         "'.' should only occur at end of builtin type list!");
3882
3883  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3884  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3885    return getFunctionNoProtoType(ResType);
3886  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3887                         TypeStr[0] == '.', 0);
3888}
3889