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