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