blob: 80bda841feb5ecc3febec51951a8b09cb41663bd [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000025#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000026#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000027#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000028#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000029#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/Support/raw_ostream.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000031
Chris Lattnerddc135e2006-11-10 06:34:16 +000032using namespace clang;
33
Steve Naroff0af91202007-04-27 21:51:21 +000034enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Douglas Gregor7dbfb462010-06-16 21:09:37 +000038void
39ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
40 TemplateTemplateParmDecl *Parm) {
41 ID.AddInteger(Parm->getDepth());
42 ID.AddInteger(Parm->getPosition());
43 // FIXME: Parameter pack
44
45 TemplateParameterList *Params = Parm->getTemplateParameters();
46 ID.AddInteger(Params->size());
47 for (TemplateParameterList::const_iterator P = Params->begin(),
48 PEnd = Params->end();
49 P != PEnd; ++P) {
50 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
51 ID.AddInteger(0);
52 ID.AddBoolean(TTP->isParameterPack());
53 continue;
54 }
55
56 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
57 ID.AddInteger(1);
58 // FIXME: Parameter pack
59 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
60 continue;
61 }
62
63 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
64 ID.AddInteger(2);
65 Profile(ID, TTP);
66 }
67}
68
69TemplateTemplateParmDecl *
70ASTContext::getCanonicalTemplateTemplateParmDecl(
71 TemplateTemplateParmDecl *TTP) {
72 // Check if we already have a canonical template template parameter.
73 llvm::FoldingSetNodeID ID;
74 CanonicalTemplateTemplateParm::Profile(ID, TTP);
75 void *InsertPos = 0;
76 CanonicalTemplateTemplateParm *Canonical
77 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
78 if (Canonical)
79 return Canonical->getParam();
80
81 // Build a canonical template parameter list.
82 TemplateParameterList *Params = TTP->getTemplateParameters();
83 llvm::SmallVector<NamedDecl *, 4> CanonParams;
84 CanonParams.reserve(Params->size());
85 for (TemplateParameterList::const_iterator P = Params->begin(),
86 PEnd = Params->end();
87 P != PEnd; ++P) {
88 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
89 CanonParams.push_back(
90 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
91 SourceLocation(), TTP->getDepth(),
92 TTP->getIndex(), 0, false,
93 TTP->isParameterPack()));
94 else if (NonTypeTemplateParmDecl *NTTP
95 = dyn_cast<NonTypeTemplateParmDecl>(*P))
96 CanonParams.push_back(
97 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
98 SourceLocation(), NTTP->getDepth(),
99 NTTP->getPosition(), 0,
100 getCanonicalType(NTTP->getType()),
101 0));
102 else
103 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
104 cast<TemplateTemplateParmDecl>(*P)));
105 }
106
107 TemplateTemplateParmDecl *CanonTTP
108 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
109 SourceLocation(), TTP->getDepth(),
110 TTP->getPosition(), 0,
111 TemplateParameterList::Create(*this, SourceLocation(),
112 SourceLocation(),
113 CanonParams.data(),
114 CanonParams.size(),
115 SourceLocation()));
116
117 // Get the new insert position for the node we care about.
118 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
119 assert(Canonical == 0 && "Shouldn't be in the map!");
120 (void)Canonical;
121
122 // Create the canonical template template parameter entry.
123 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
124 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
125 return CanonTTP;
126}
127
Chris Lattner465fa322008-10-05 17:34:18 +0000128ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000129 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000130 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000131 Builtin::Context &builtins,
Mike Stump11289f42009-09-09 15:08:12 +0000132 bool FreeMem, unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000133 TemplateSpecializationTypes(this_()),
134 DependentTemplateSpecializationTypes(this_()),
Mike Stump11289f42009-09-09 15:08:12 +0000135 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Fariborz Jahaniane804c282010-04-23 17:41:07 +0000136 NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000137 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000138 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000139 NullTypeSourceInfo(QualType()),
Douglas Gregor9507d462010-03-19 22:13:20 +0000140 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000141 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000142 BuiltinInfo(builtins),
143 DeclarationNames(*this),
144 ExternalSource(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000145 LastSDM(0, 0),
146 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000147 ObjCIdRedefinitionType = QualType();
148 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian04b258c2009-11-25 23:07:42 +0000149 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000150 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000151 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000152 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000153}
154
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000155ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000156 // Release the DenseMaps associated with DeclContext objects.
157 // FIXME: Is this the ideal solution?
158 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000159
Douglas Gregor1a809332010-05-23 18:26:36 +0000160 if (!FreeMemory) {
161 // Call all of the deallocation functions.
162 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
163 Deallocations[I].first(Deallocations[I].second);
164 }
165
Douglas Gregor832940b2010-03-02 23:58:15 +0000166 // Release all of the memory associated with overridden C++ methods.
167 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
168 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
169 OM != OMEnd; ++OM)
170 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000171
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000172 if (FreeMemory) {
173 // Deallocate all the types.
174 while (!Types.empty()) {
175 Types.back()->Destroy(*this);
176 Types.pop_back();
177 }
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000178
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000179 for (llvm::FoldingSet<ExtQuals>::iterator
180 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
181 // Increment in loop to prevent using deallocated memory.
John McCall8ccfcb52009-09-24 19:53:00 +0000182 Deallocate(&*I++);
Nuno Lopese013c7f2008-12-17 22:30:25 +0000183 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000184
Ted Kremenekc3015a92010-03-08 20:56:29 +0000185 for (llvm::DenseMap<const ObjCContainerDecl*,
186 const ASTRecordLayout*>::iterator
187 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
188 // Increment in loop to prevent using deallocated memory.
189 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
190 R->Destroy(*this);
191 }
Nuno Lopese013c7f2008-12-17 22:30:25 +0000192 }
193
Ted Kremenek076baeb2010-06-08 23:00:58 +0000194 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
195 // even when using the BumpPtrAllocator because they can contain
196 // DenseMaps.
197 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
198 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
199 // Increment in loop to prevent using deallocated memory.
200 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
201 R->Destroy(*this);
202 }
203
Douglas Gregorf21eb492009-03-26 23:50:42 +0000204 // Destroy nested-name-specifiers.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000205 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
206 NNS = NestedNameSpecifiers.begin(),
Mike Stump11289f42009-09-09 15:08:12 +0000207 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000208 NNS != NNSEnd; ) {
209 // Increment in loop to prevent using deallocated memory.
Douglas Gregorc741fb12009-03-27 23:54:10 +0000210 (*NNS++).Destroy(*this);
Ted Kremenek40ee0cc2009-12-23 21:13:52 +0000211 }
Douglas Gregorf21eb492009-03-26 23:50:42 +0000212
213 if (GlobalNestedNameSpecifier)
214 GlobalNestedNameSpecifier->Destroy(*this);
215
Eli Friedmane2bbfe22008-05-27 03:08:09 +0000216 TUDecl->Destroy(*this);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000217}
218
Douglas Gregor1a809332010-05-23 18:26:36 +0000219void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
220 Deallocations.push_back(std::make_pair(Callback, Data));
221}
222
Mike Stump11289f42009-09-09 15:08:12 +0000223void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000224ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
225 ExternalSource.reset(Source.take());
226}
227
Chris Lattner4eb445d2007-01-26 01:27:23 +0000228void ASTContext::PrintStats() const {
229 fprintf(stderr, "*** AST Context Stats:\n");
230 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000231
Douglas Gregora30d0462009-05-26 14:40:08 +0000232 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000233#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000234#define ABSTRACT_TYPE(Name, Parent)
235#include "clang/AST/TypeNodes.def"
236 0 // Extra
237 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000238
Chris Lattner4eb445d2007-01-26 01:27:23 +0000239 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
240 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000241 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000242 }
243
Douglas Gregora30d0462009-05-26 14:40:08 +0000244 unsigned Idx = 0;
245 unsigned TotalBytes = 0;
246#define TYPE(Name, Parent) \
247 if (counts[Idx]) \
248 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
249 TotalBytes += counts[Idx] * sizeof(Name##Type); \
250 ++Idx;
251#define ABSTRACT_TYPE(Name, Parent)
252#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000253
Douglas Gregora30d0462009-05-26 14:40:08 +0000254 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000255
256 if (ExternalSource.get()) {
257 fprintf(stderr, "\n");
258 ExternalSource->PrintStats();
259 }
Chris Lattner4eb445d2007-01-26 01:27:23 +0000260}
261
262
John McCall48f2d582009-10-23 23:03:21 +0000263void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000264 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000265 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000266 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000267}
268
Chris Lattner970e54e2006-11-12 00:37:36 +0000269void ASTContext::InitBuiltinTypes() {
270 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000271
Chris Lattner970e54e2006-11-12 00:37:36 +0000272 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000273 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattner970e54e2006-11-12 00:37:36 +0000275 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000276 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000277 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000278 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000279 InitBuiltinType(CharTy, BuiltinType::Char_S);
280 else
281 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000282 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000283 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
284 InitBuiltinType(ShortTy, BuiltinType::Short);
285 InitBuiltinType(IntTy, BuiltinType::Int);
286 InitBuiltinType(LongTy, BuiltinType::Long);
287 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000288
Chris Lattner970e54e2006-11-12 00:37:36 +0000289 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000290 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
291 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
292 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
293 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
294 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000295
Chris Lattner970e54e2006-11-12 00:37:36 +0000296 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000297 InitBuiltinType(FloatTy, BuiltinType::Float);
298 InitBuiltinType(DoubleTy, BuiltinType::Double);
299 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000300
Chris Lattnerf122cef2009-04-30 02:43:43 +0000301 // GNU extension, 128-bit integers.
302 InitBuiltinType(Int128Ty, BuiltinType::Int128);
303 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
304
Chris Lattner007cb022009-02-26 23:43:47 +0000305 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
306 InitBuiltinType(WCharTy, BuiltinType::WChar);
307 else // C99
308 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000309
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000310 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
311 InitBuiltinType(Char16Ty, BuiltinType::Char16);
312 else // C99
313 Char16Ty = getFromTargetType(Target.getChar16Type());
314
315 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
316 InitBuiltinType(Char32Ty, BuiltinType::Char32);
317 else // C99
318 Char32Ty = getFromTargetType(Target.getChar32Type());
319
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000320 // Placeholder type for functions.
Douglas Gregor4619e432008-12-05 23:32:09 +0000321 InitBuiltinType(OverloadTy, BuiltinType::Overload);
322
323 // Placeholder type for type-dependent expressions whose type is
324 // completely unknown. No code should ever check a type against
325 // DependentTy and users should never see it; however, it is here to
326 // help diagnose failures to properly check for type-dependent
327 // expressions.
328 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000329
Mike Stump11289f42009-09-09 15:08:12 +0000330 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000331 // not yet been deduced.
332 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000333
Chris Lattner970e54e2006-11-12 00:37:36 +0000334 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000335 FloatComplexTy = getComplexType(FloatTy);
336 DoubleComplexTy = getComplexType(DoubleTy);
337 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000338
Steve Naroff66e9f332007-10-15 14:41:52 +0000339 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000340
Steve Naroff1329fa02009-07-15 18:40:39 +0000341 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
342 ObjCIdTypedefType = QualType();
343 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000344 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000345
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000346 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000347 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
348 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000349 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000350
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000351 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000352
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000353 // void * type
354 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000355
356 // nullptr type (C++0x 2.14.7)
357 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000358}
359
Douglas Gregor86d142a2009-10-08 07:24:58 +0000360MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000361ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000362 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000363 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000364 = InstantiatedFromStaticDataMember.find(Var);
365 if (Pos == InstantiatedFromStaticDataMember.end())
366 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000367
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000368 return Pos->second;
369}
370
Mike Stump11289f42009-09-09 15:08:12 +0000371void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000372ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
373 TemplateSpecializationKind TSK) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000374 assert(Inst->isStaticDataMember() && "Not a static data member");
375 assert(Tmpl->isStaticDataMember() && "Not a static data member");
376 assert(!InstantiatedFromStaticDataMember[Inst] &&
377 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000378 InstantiatedFromStaticDataMember[Inst]
379 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000380}
381
John McCalle61f2ba2009-11-18 02:36:19 +0000382NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000383ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000384 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000385 = InstantiatedFromUsingDecl.find(UUD);
386 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000387 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000388
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000389 return Pos->second;
390}
391
392void
John McCallb96ec562009-12-04 22:46:56 +0000393ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
394 assert((isa<UsingDecl>(Pattern) ||
395 isa<UnresolvedUsingValueDecl>(Pattern) ||
396 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
397 "pattern decl is not a using decl");
398 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
399 InstantiatedFromUsingDecl[Inst] = Pattern;
400}
401
402UsingShadowDecl *
403ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
404 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
405 = InstantiatedFromUsingShadowDecl.find(Inst);
406 if (Pos == InstantiatedFromUsingShadowDecl.end())
407 return 0;
408
409 return Pos->second;
410}
411
412void
413ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
414 UsingShadowDecl *Pattern) {
415 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
416 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000417}
418
Anders Carlsson5da84842009-09-01 04:26:58 +0000419FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
420 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
421 = InstantiatedFromUnnamedFieldDecl.find(Field);
422 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
423 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000424
Anders Carlsson5da84842009-09-01 04:26:58 +0000425 return Pos->second;
426}
427
428void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
429 FieldDecl *Tmpl) {
430 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
431 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
432 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
433 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000434
Anders Carlsson5da84842009-09-01 04:26:58 +0000435 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
436}
437
Douglas Gregor832940b2010-03-02 23:58:15 +0000438ASTContext::overridden_cxx_method_iterator
439ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
440 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
441 = OverriddenMethods.find(Method);
442 if (Pos == OverriddenMethods.end())
443 return 0;
444
445 return Pos->second.begin();
446}
447
448ASTContext::overridden_cxx_method_iterator
449ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
450 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
451 = OverriddenMethods.find(Method);
452 if (Pos == OverriddenMethods.end())
453 return 0;
454
455 return Pos->second.end();
456}
457
458void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
459 const CXXMethodDecl *Overridden) {
460 OverriddenMethods[Method].push_back(Overridden);
461}
462
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000463namespace {
Mike Stump11289f42009-09-09 15:08:12 +0000464 class BeforeInTranslationUnit
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000465 : std::binary_function<SourceRange, SourceRange, bool> {
466 SourceManager *SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +0000467
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000468 public:
469 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump11289f42009-09-09 15:08:12 +0000470
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000471 bool operator()(SourceRange X, SourceRange Y) {
472 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
473 }
474 };
475}
476
Chris Lattner53cfe802007-07-18 17:52:12 +0000477//===----------------------------------------------------------------------===//
478// Type Sizing and Analysis
479//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000480
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000481/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
482/// scalar floating point type.
483const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000484 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000485 assert(BT && "Not a floating point type!");
486 switch (BT->getKind()) {
487 default: assert(0 && "Not a floating point type!");
488 case BuiltinType::Float: return Target.getFloatFormat();
489 case BuiltinType::Double: return Target.getDoubleFormat();
490 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
491 }
492}
493
Ken Dyck160146e2010-01-27 17:10:57 +0000494/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000495/// specified decl. Note that bitfields do not have a valid alignment, so
496/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000497/// If @p RefAsPointee, references are treated like their underlying type
498/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck160146e2010-01-27 17:10:57 +0000499CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedman19a546c2009-02-22 02:56:25 +0000500 unsigned Align = Target.getCharWidth();
501
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000502 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Alexis Hunt96d5c762009-11-21 08:43:09 +0000503 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedman19a546c2009-02-22 02:56:25 +0000504
Chris Lattner68061312009-01-24 21:53:27 +0000505 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
506 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000507 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000508 if (RefAsPointee)
509 T = RT->getPointeeType();
510 else
511 T = getPointerType(RT->getPointeeType());
512 }
513 if (!T->isIncompleteType() && !T->isFunctionType()) {
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000514 unsigned MinWidth = Target.getLargeArrayMinWidth();
515 unsigned ArrayAlign = Target.getLargeArrayAlign();
516 if (isa<VariableArrayType>(T) && MinWidth != 0)
517 Align = std::max(Align, ArrayAlign);
518 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
519 unsigned Size = getTypeSize(CT);
520 if (MinWidth != 0 && MinWidth <= Size)
521 Align = std::max(Align, ArrayAlign);
522 }
Anders Carlsson9b5038e2009-04-10 04:47:03 +0000523 // Incomplete or function types default to 1.
Eli Friedman19a546c2009-02-22 02:56:25 +0000524 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
525 T = cast<ArrayType>(T)->getElementType();
526
527 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
528 }
Charles Davis3fc51072010-02-23 04:52:00 +0000529 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
530 // In the case of a field in a packed struct, we want the minimum
531 // of the alignment of the field and the alignment of the struct.
532 Align = std::min(Align,
533 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
534 }
Chris Lattner68061312009-01-24 21:53:27 +0000535 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000536
Ken Dyck160146e2010-01-27 17:10:57 +0000537 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattner68061312009-01-24 21:53:27 +0000538}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000539
John McCall87fe5d52010-05-20 01:18:31 +0000540std::pair<CharUnits, CharUnits>
541ASTContext::getTypeInfoInChars(const Type *T) {
542 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
543 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
544 CharUnits::fromQuantity(Info.second / getCharWidth()));
545}
546
547std::pair<CharUnits, CharUnits>
548ASTContext::getTypeInfoInChars(QualType T) {
549 return getTypeInfoInChars(T.getTypePtr());
550}
551
Chris Lattner983a8bb2007-07-13 22:13:22 +0000552/// getTypeSize - Return the size of the specified type, in bits. This method
553/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000554///
555/// FIXME: Pointers into different addr spaces could have different sizes and
556/// alignment requirements: getPointerInfo should take an AddrSpace, this
557/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000558std::pair<uint64_t, unsigned>
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000559ASTContext::getTypeInfo(const Type *T) {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000560 uint64_t Width=0;
561 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000562 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000563#define TYPE(Class, Base)
564#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000565#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000566#define DEPENDENT_TYPE(Class, Base) case Type::Class:
567#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000568 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000569 break;
570
Chris Lattner355332d2007-07-13 22:27:08 +0000571 case Type::FunctionNoProto:
572 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000573 // GCC extension: alignof(function) = 32 bits
574 Width = 0;
575 Align = 32;
576 break;
577
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000578 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000579 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000580 Width = 0;
581 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
582 break;
583
Steve Naroff5c131802007-08-30 01:06:46 +0000584 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000585 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000586
Chris Lattner37e05872008-03-05 18:54:05 +0000587 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000588 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000589 Align = EltInfo.second;
590 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000591 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000592 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000593 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000594 const VectorType *VT = cast<VectorType>(T);
595 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
596 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000597 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000598 // If the alignment is not a power of 2, round up to the next power of 2.
599 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000600 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000601 Align = llvm::NextPowerOf2(Align);
602 Width = llvm::RoundUpToAlignment(Width, Align);
603 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000604 break;
605 }
Chris Lattner647fb222007-07-18 18:26:58 +0000606
Chris Lattner7570e9c2008-03-08 08:52:55 +0000607 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000608 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000609 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000610 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000611 // GCC extension: alignof(void) = 8 bits.
612 Width = 0;
613 Align = 8;
614 break;
615
Chris Lattner6a4f7452007-12-19 19:23:28 +0000616 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000617 Width = Target.getBoolWidth();
618 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000619 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000620 case BuiltinType::Char_S:
621 case BuiltinType::Char_U:
622 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000623 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000624 Width = Target.getCharWidth();
625 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000626 break;
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000627 case BuiltinType::WChar:
628 Width = Target.getWCharWidth();
629 Align = Target.getWCharAlign();
630 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000631 case BuiltinType::Char16:
632 Width = Target.getChar16Width();
633 Align = Target.getChar16Align();
634 break;
635 case BuiltinType::Char32:
636 Width = Target.getChar32Width();
637 Align = Target.getChar32Align();
638 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000639 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000640 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000641 Width = Target.getShortWidth();
642 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000643 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000644 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000645 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000646 Width = Target.getIntWidth();
647 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000648 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000649 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000650 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000651 Width = Target.getLongWidth();
652 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000653 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000654 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000655 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000656 Width = Target.getLongLongWidth();
657 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000658 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000659 case BuiltinType::Int128:
660 case BuiltinType::UInt128:
661 Width = 128;
662 Align = 128; // int128_t is 128-bit aligned on all targets.
663 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000664 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000665 Width = Target.getFloatWidth();
666 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000667 break;
668 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000669 Width = Target.getDoubleWidth();
670 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000671 break;
672 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000673 Width = Target.getLongDoubleWidth();
674 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000675 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000676 case BuiltinType::NullPtr:
677 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
678 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000679 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000680 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000681 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000682 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000683 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000684 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000685 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000686 case Type::BlockPointer: {
687 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
688 Width = Target.getPointerWidth(AS);
689 Align = Target.getPointerAlign(AS);
690 break;
691 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000692 case Type::LValueReference:
693 case Type::RValueReference: {
694 // alignof and sizeof should never enter this code path here, so we go
695 // the pointer route.
696 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
697 Width = Target.getPointerWidth(AS);
698 Align = Target.getPointerAlign(AS);
699 break;
700 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000701 case Type::Pointer: {
702 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000703 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000704 Align = Target.getPointerAlign(AS);
705 break;
706 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000707 case Type::MemberPointer: {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000708 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +0000709 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000710 getTypeInfo(getPointerDiffType());
711 Width = PtrDiffInfo.first;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000712 if (Pointee->isFunctionType())
713 Width *= 2;
Anders Carlsson32440a02009-05-17 02:06:04 +0000714 Align = PtrDiffInfo.second;
715 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000716 }
Chris Lattner647fb222007-07-18 18:26:58 +0000717 case Type::Complex: {
718 // Complex types have the same alignment as their elements, but twice the
719 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000720 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000721 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000722 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000723 Align = EltInfo.second;
724 break;
725 }
John McCall8b07ec22010-05-15 11:32:37 +0000726 case Type::ObjCObject:
727 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000728 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000729 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000730 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
731 Width = Layout.getSize();
732 Align = Layout.getAlignment();
733 break;
734 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000735 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000736 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000737 const TagType *TT = cast<TagType>(T);
738
739 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000740 Width = 1;
741 Align = 1;
742 break;
743 }
Mike Stump11289f42009-09-09 15:08:12 +0000744
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000745 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000746 return getTypeInfo(ET->getDecl()->getIntegerType());
747
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000748 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000749 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
750 Width = Layout.getSize();
751 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000752 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000753 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000754
Chris Lattner63d2b362009-10-22 05:17:15 +0000755 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000756 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
757 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000758
Douglas Gregoref462e62009-04-30 17:32:17 +0000759 case Type::Typedef: {
760 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000761 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Alexis Hunt96d5c762009-11-21 08:43:09 +0000762 Align = std::max(Aligned->getMaxAlignment(),
763 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregoref462e62009-04-30 17:32:17 +0000764 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
765 } else
766 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordc572a32009-03-30 22:58:21 +0000767 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000768 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000769
770 case Type::TypeOfExpr:
771 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
772 .getTypePtr());
773
774 case Type::TypeOf:
775 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
776
Anders Carlsson81df7b82009-06-24 19:06:50 +0000777 case Type::Decltype:
778 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
779 .getTypePtr());
780
Abramo Bagnara6150c882010-05-11 21:36:43 +0000781 case Type::Elaborated:
782 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregoref462e62009-04-30 17:32:17 +0000784 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000785 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000786 "Cannot request the size of a dependent type");
787 // FIXME: this is likely to be wrong once we support template
788 // aliases, since a template alias could refer to a typedef that
789 // has an __aligned__ attribute on it.
790 return getTypeInfo(getCanonicalType(T));
791 }
Mike Stump11289f42009-09-09 15:08:12 +0000792
Chris Lattner53cfe802007-07-18 17:52:12 +0000793 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000794 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000795}
796
Ken Dyck8c89d592009-12-22 14:23:30 +0000797/// getTypeSizeInChars - Return the size of the specified type, in characters.
798/// This method does not work on incomplete types.
799CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck40775002010-01-11 17:06:35 +0000800 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000801}
802CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck40775002010-01-11 17:06:35 +0000803 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyck8c89d592009-12-22 14:23:30 +0000804}
805
Ken Dycka6046ab2010-01-26 17:25:18 +0000806/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000807/// characters. This method does not work on incomplete types.
808CharUnits ASTContext::getTypeAlignInChars(QualType T) {
809 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
810}
811CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
812 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
813}
814
Chris Lattnera3402cd2009-01-27 18:08:34 +0000815/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
816/// type for the current target in bits. This can be different than the ABI
817/// alignment in cases where it is beneficial for performance to overalign
818/// a data type.
819unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
820 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000821
822 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000823 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000824 T = CT->getElementType().getTypePtr();
825 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
826 T->isSpecificBuiltinType(BuiltinType::LongLong))
827 return std::max(ABIAlign, (unsigned)getTypeSize(T));
828
Chris Lattnera3402cd2009-01-27 18:08:34 +0000829 return ABIAlign;
830}
831
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000832static void CollectLocalObjCIvars(ASTContext *Ctx,
833 const ObjCInterfaceDecl *OI,
834 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000835 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
836 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner5b36ddb2009-03-31 08:48:01 +0000837 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanianf327e892008-12-17 21:40:49 +0000838 if (!IVDecl->isInvalidDecl())
839 Fields.push_back(cast<FieldDecl>(IVDecl));
840 }
841}
842
Daniel Dunbare4f25b72009-04-22 17:43:55 +0000843void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
844 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
845 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
846 CollectObjCIvars(SuperClass, Fields);
847 CollectLocalObjCIvars(this, OI, Fields);
848}
849
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000850/// ShallowCollectObjCIvars -
851/// Collect all ivars, including those synthesized, in the current class.
852///
853void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000854 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000855 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
856 E = OI->ivar_end(); I != E; ++I) {
857 Ivars.push_back(*I);
858 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000859
860 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000861}
862
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000863/// CollectNonClassIvars -
864/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek86838aa2010-03-11 19:44:54 +0000865/// This includes synthesized ivars (via @synthesize) and those in
866// class's @implementation.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000867///
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000868void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000869 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000870 // Find ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000871 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
872 CDecl = CDecl->getNextClassExtension()) {
Fariborz Jahanianafe13862010-02-23 01:26:30 +0000873 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
874 E = CDecl->ivar_end(); I != E; ++I) {
875 Ivars.push_back(*I);
876 }
877 }
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000878
Ted Kremenek86838aa2010-03-11 19:44:54 +0000879 // Also add any ivar defined in this class's implementation. This
880 // includes synthesized ivars.
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000881 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
882 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
883 E = ImplDecl->ivar_end(); I != E; ++I)
884 Ivars.push_back(*I);
885 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000886}
887
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000888/// CollectInheritedProtocols - Collect all protocols in current class and
889/// those inherited by it.
890void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000891 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000892 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
893 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
894 PE = OI->protocol_end(); P != PE; ++P) {
895 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000896 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000897 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000898 PE = Proto->protocol_end(); P != PE; ++P) {
899 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000900 CollectInheritedProtocols(*P, Protocols);
901 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +0000902 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000903
904 // Categories of this Interface.
905 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
906 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
907 CollectInheritedProtocols(CDeclChain, Protocols);
908 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
909 while (SD) {
910 CollectInheritedProtocols(SD, Protocols);
911 SD = SD->getSuperClass();
912 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000913 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000914 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
915 PE = OC->protocol_end(); P != PE; ++P) {
916 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000917 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000918 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
919 PE = Proto->protocol_end(); P != PE; ++P)
920 CollectInheritedProtocols(*P, Protocols);
921 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000922 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000923 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
924 PE = OP->protocol_end(); P != PE; ++P) {
925 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000926 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000927 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
928 PE = Proto->protocol_end(); P != PE; ++P)
929 CollectInheritedProtocols(*P, Protocols);
930 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000931 }
932}
933
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000934unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
935 unsigned count = 0;
936 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000937 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
938 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000939 count += CDecl->ivar_size();
940
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +0000941 // Count ivar defined in this class's implementation. This
942 // includes synthesized ivars.
943 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +0000944 count += ImplDecl->ivar_size();
945
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000946 return count;
947}
948
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000949/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
950ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
951 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
952 I = ObjCImpls.find(D);
953 if (I != ObjCImpls.end())
954 return cast<ObjCImplementationDecl>(I->second);
955 return 0;
956}
957/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
958ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
959 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
960 I = ObjCImpls.find(D);
961 if (I != ObjCImpls.end())
962 return cast<ObjCCategoryImplDecl>(I->second);
963 return 0;
964}
965
966/// \brief Set the implementation of ObjCInterfaceDecl.
967void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
968 ObjCImplementationDecl *ImplD) {
969 assert(IFaceD && ImplD && "Passed null params");
970 ObjCImpls[IFaceD] = ImplD;
971}
972/// \brief Set the implementation of ObjCCategoryDecl.
973void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
974 ObjCCategoryImplDecl *ImplD) {
975 assert(CatD && ImplD && "Passed null params");
976 ObjCImpls[CatD] = ImplD;
977}
978
John McCallbcd03502009-12-07 02:54:59 +0000979/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000980///
John McCallbcd03502009-12-07 02:54:59 +0000981/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000982/// the TypeLoc wrappers.
983///
984/// \param T the type that will be the basis for type source info. This type
985/// should refer to how the declarator was written in source code, not to
986/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +0000987TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall26fe7e02009-10-21 00:23:54 +0000988 unsigned DataSize) {
989 if (!DataSize)
990 DataSize = TypeLoc::getFullDataSizeForType(T);
991 else
992 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +0000993 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +0000994
John McCallbcd03502009-12-07 02:54:59 +0000995 TypeSourceInfo *TInfo =
996 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
997 new (TInfo) TypeSourceInfo(T);
998 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +0000999}
1000
John McCallbcd03502009-12-07 02:54:59 +00001001TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCall3665e002009-10-23 21:14:09 +00001002 SourceLocation L) {
John McCallbcd03502009-12-07 02:54:59 +00001003 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCall3665e002009-10-23 21:14:09 +00001004 DI->getTypeLoc().initialize(L);
1005 return DI;
1006}
1007
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001008const ASTRecordLayout &
1009ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1010 return getObjCLayout(D, 0);
1011}
1012
1013const ASTRecordLayout &
1014ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1015 return getObjCLayout(D->getClassInterface(), D);
1016}
1017
Chris Lattner983a8bb2007-07-13 22:13:22 +00001018//===----------------------------------------------------------------------===//
1019// Type creation/memoization methods
1020//===----------------------------------------------------------------------===//
1021
John McCall8ccfcb52009-09-24 19:53:00 +00001022QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1023 unsigned Fast = Quals.getFastQualifiers();
1024 Quals.removeFastQualifiers();
1025
1026 // Check if we've already instantiated this type.
1027 llvm::FoldingSetNodeID ID;
1028 ExtQuals::Profile(ID, TypeNode, Quals);
1029 void *InsertPos = 0;
1030 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1031 assert(EQ->getQualifiers() == Quals);
1032 QualType T = QualType(EQ, Fast);
1033 return T;
1034 }
1035
John McCall90d1c2d2009-09-24 23:30:46 +00001036 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001037 ExtQualNodes.InsertNode(New, InsertPos);
1038 QualType T = QualType(New, Fast);
1039 return T;
1040}
1041
1042QualType ASTContext::getVolatileType(QualType T) {
1043 QualType CanT = getCanonicalType(T);
1044 if (CanT.isVolatileQualified()) return T;
1045
1046 QualifierCollector Quals;
1047 const Type *TypeNode = Quals.strip(T);
1048 Quals.addVolatile();
1049
1050 return getExtQualType(TypeNode, Quals);
1051}
1052
Fariborz Jahanianece85822009-02-17 18:27:45 +00001053QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001054 QualType CanT = getCanonicalType(T);
1055 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001056 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001057
John McCall8ccfcb52009-09-24 19:53:00 +00001058 // If we are composing extended qualifiers together, merge together
1059 // into one ExtQuals node.
1060 QualifierCollector Quals;
1061 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001062
John McCall8ccfcb52009-09-24 19:53:00 +00001063 // If this type already has an address space specified, it cannot get
1064 // another one.
1065 assert(!Quals.hasAddressSpace() &&
1066 "Type cannot be in multiple addr spaces!");
1067 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001068
John McCall8ccfcb52009-09-24 19:53:00 +00001069 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001070}
1071
Chris Lattnerd60183d2009-02-18 22:53:11 +00001072QualType ASTContext::getObjCGCQualType(QualType T,
John McCall8ccfcb52009-09-24 19:53:00 +00001073 Qualifiers::GC GCAttr) {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001074 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001075 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001076 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001077
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001078 if (T->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001079 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001080 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001081 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1082 return getPointerType(ResultType);
1083 }
1084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
John McCall8ccfcb52009-09-24 19:53:00 +00001086 // If we are composing extended qualifiers together, merge together
1087 // into one ExtQuals node.
1088 QualifierCollector Quals;
1089 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001090
John McCall8ccfcb52009-09-24 19:53:00 +00001091 // If this type already has an ObjCGC specified, it cannot get
1092 // another one.
1093 assert(!Quals.hasObjCGCAttr() &&
1094 "Type cannot have multiple ObjCGCs!");
1095 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001096
John McCall8ccfcb52009-09-24 19:53:00 +00001097 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001098}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001099
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001100static QualType getExtFunctionType(ASTContext& Context, QualType T,
1101 const FunctionType::ExtInfo &Info) {
John McCall8ccfcb52009-09-24 19:53:00 +00001102 QualType ResultType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001103 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1104 QualType Pointee = Pointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001105 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001106 if (ResultType == Pointee)
1107 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001108
1109 ResultType = Context.getPointerType(ResultType);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001110 } else if (const BlockPointerType *BlockPointer
1111 = T->getAs<BlockPointerType>()) {
1112 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001113 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001114 if (ResultType == Pointee)
1115 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001116
1117 ResultType = Context.getBlockPointerType(ResultType);
1118 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001119 if (F->getExtInfo() == Info)
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001120 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001121
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001122 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregor8c940862010-01-18 17:14:39 +00001123 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001124 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001125 } else {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001126 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall8ccfcb52009-09-24 19:53:00 +00001127 ResultType
Douglas Gregor8c940862010-01-18 17:14:39 +00001128 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1129 FPT->getNumArgs(), FPT->isVariadic(),
1130 FPT->getTypeQuals(),
1131 FPT->hasExceptionSpec(),
1132 FPT->hasAnyExceptionSpec(),
1133 FPT->getNumExceptions(),
1134 FPT->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001135 Info);
John McCall8ccfcb52009-09-24 19:53:00 +00001136 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001137 } else
1138 return T;
Douglas Gregor8c940862010-01-18 17:14:39 +00001139
1140 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1141}
1142
1143QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001144 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001145 return getExtFunctionType(*this, T,
1146 Info.withNoReturn(AddNoReturn));
Douglas Gregor8c940862010-01-18 17:14:39 +00001147}
1148
1149QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001150 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001151 return getExtFunctionType(*this, T,
1152 Info.withCallingConv(CallConv));
Mike Stump8c5d7992009-07-25 21:26:53 +00001153}
1154
Rafael Espindola49b85ab2010-03-30 22:15:11 +00001155QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1156 FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1157 return getExtFunctionType(*this, T,
1158 Info.withRegParm(RegParm));
1159}
1160
Chris Lattnerc6395932007-06-22 20:56:16 +00001161/// getComplexType - Return the uniqued reference to the type for a complex
1162/// number with the specified element type.
1163QualType ASTContext::getComplexType(QualType T) {
1164 // Unique pointers, to guarantee there is only one pointer of a particular
1165 // structure.
1166 llvm::FoldingSetNodeID ID;
1167 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Chris Lattnerc6395932007-06-22 20:56:16 +00001169 void *InsertPos = 0;
1170 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1171 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001172
Chris Lattnerc6395932007-06-22 20:56:16 +00001173 // If the pointee type isn't canonical, this won't be a canonical type either,
1174 // so fill in the canonical type field.
1175 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001176 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001177 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001178
Chris Lattnerc6395932007-06-22 20:56:16 +00001179 // Get the new insert position for the node we care about.
1180 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001181 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001182 }
John McCall90d1c2d2009-09-24 23:30:46 +00001183 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001184 Types.push_back(New);
1185 ComplexTypes.InsertNode(New, InsertPos);
1186 return QualType(New, 0);
1187}
1188
Chris Lattner970e54e2006-11-12 00:37:36 +00001189/// getPointerType - Return the uniqued reference to the type for a pointer to
1190/// the specified type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001191QualType ASTContext::getPointerType(QualType T) {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001192 // Unique pointers, to guarantee there is only one pointer of a particular
1193 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001194 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001195 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001196
Chris Lattner67521df2007-01-27 01:29:36 +00001197 void *InsertPos = 0;
1198 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001199 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001200
Chris Lattner7ccecb92006-11-12 08:50:50 +00001201 // If the pointee type isn't canonical, this won't be a canonical type either,
1202 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001203 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001204 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001205 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001206
Chris Lattner67521df2007-01-27 01:29:36 +00001207 // Get the new insert position for the node we care about.
1208 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001209 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001210 }
John McCall90d1c2d2009-09-24 23:30:46 +00001211 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001212 Types.push_back(New);
1213 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001214 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001215}
1216
Mike Stump11289f42009-09-09 15:08:12 +00001217/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001218/// a pointer to the specified block.
1219QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff0ac012832008-08-28 19:20:44 +00001220 assert(T->isFunctionType() && "block of function types only");
1221 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001222 // structure.
1223 llvm::FoldingSetNodeID ID;
1224 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001225
Steve Naroffec33ed92008-08-27 16:04:49 +00001226 void *InsertPos = 0;
1227 if (BlockPointerType *PT =
1228 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1229 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001230
1231 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001232 // type either so fill in the canonical type field.
1233 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001234 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001235 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001236
Steve Naroffec33ed92008-08-27 16:04:49 +00001237 // Get the new insert position for the node we care about.
1238 BlockPointerType *NewIP =
1239 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001240 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001241 }
John McCall90d1c2d2009-09-24 23:30:46 +00001242 BlockPointerType *New
1243 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001244 Types.push_back(New);
1245 BlockPointerTypes.InsertNode(New, InsertPos);
1246 return QualType(New, 0);
1247}
1248
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001249/// getLValueReferenceType - Return the uniqued reference to the type for an
1250/// lvalue reference to the specified type.
John McCallfc93cf92009-10-22 22:37:11 +00001251QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Bill Wendling3708c182007-05-27 10:15:43 +00001252 // Unique pointers, to guarantee there is only one pointer of a particular
1253 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001254 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001255 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001256
1257 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001258 if (LValueReferenceType *RT =
1259 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001260 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001261
John McCallfc93cf92009-10-22 22:37:11 +00001262 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1263
Bill Wendling3708c182007-05-27 10:15:43 +00001264 // If the referencee type isn't canonical, this won't be a canonical type
1265 // either, so fill in the canonical type field.
1266 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001267 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1268 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1269 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001270
Bill Wendling3708c182007-05-27 10:15:43 +00001271 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001272 LValueReferenceType *NewIP =
1273 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001274 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001275 }
1276
John McCall90d1c2d2009-09-24 23:30:46 +00001277 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001278 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1279 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001280 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001281 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001282
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001283 return QualType(New, 0);
1284}
1285
1286/// getRValueReferenceType - Return the uniqued reference to the type for an
1287/// rvalue reference to the specified type.
1288QualType ASTContext::getRValueReferenceType(QualType T) {
1289 // Unique pointers, to guarantee there is only one pointer of a particular
1290 // structure.
1291 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001292 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001293
1294 void *InsertPos = 0;
1295 if (RValueReferenceType *RT =
1296 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1297 return QualType(RT, 0);
1298
John McCallfc93cf92009-10-22 22:37:11 +00001299 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1300
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001301 // If the referencee type isn't canonical, this won't be a canonical type
1302 // either, so fill in the canonical type field.
1303 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001304 if (InnerRef || !T.isCanonical()) {
1305 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1306 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001307
1308 // Get the new insert position for the node we care about.
1309 RValueReferenceType *NewIP =
1310 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1311 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1312 }
1313
John McCall90d1c2d2009-09-24 23:30:46 +00001314 RValueReferenceType *New
1315 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001316 Types.push_back(New);
1317 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001318 return QualType(New, 0);
1319}
1320
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001321/// getMemberPointerType - Return the uniqued reference to the type for a
1322/// member pointer to the specified type, in the specified class.
Mike Stump11289f42009-09-09 15:08:12 +00001323QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001324 // Unique pointers, to guarantee there is only one pointer of a particular
1325 // structure.
1326 llvm::FoldingSetNodeID ID;
1327 MemberPointerType::Profile(ID, T, Cls);
1328
1329 void *InsertPos = 0;
1330 if (MemberPointerType *PT =
1331 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1332 return QualType(PT, 0);
1333
1334 // If the pointee or class type isn't canonical, this won't be a canonical
1335 // type either, so fill in the canonical type field.
1336 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001337 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001338 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1339
1340 // Get the new insert position for the node we care about.
1341 MemberPointerType *NewIP =
1342 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1343 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1344 }
John McCall90d1c2d2009-09-24 23:30:46 +00001345 MemberPointerType *New
1346 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001347 Types.push_back(New);
1348 MemberPointerTypes.InsertNode(New, InsertPos);
1349 return QualType(New, 0);
1350}
1351
Mike Stump11289f42009-09-09 15:08:12 +00001352/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001353/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001354QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001355 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001356 ArrayType::ArraySizeModifier ASM,
1357 unsigned EltTypeQuals) {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001358 assert((EltTy->isDependentType() ||
1359 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001360 "Constant array of VLAs is illegal!");
1361
Chris Lattnere2df3f92009-05-13 04:12:56 +00001362 // Convert the array size into a canonical width matching the pointer size for
1363 // the target.
1364 llvm::APInt ArySize(ArySizeIn);
1365 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001366
Chris Lattner23b7eb62007-06-15 23:05:46 +00001367 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001368 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001369
Chris Lattner36f8e652007-01-27 08:31:04 +00001370 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001371 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001372 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001373 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001374
Chris Lattner7ccecb92006-11-12 08:50:50 +00001375 // If the element type isn't canonical, this won't be a canonical type either,
1376 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001377 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001378 if (!EltTy.isCanonical()) {
Mike Stump11289f42009-09-09 15:08:12 +00001379 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001380 ASM, EltTypeQuals);
Chris Lattner36f8e652007-01-27 08:31:04 +00001381 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001382 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001383 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001384 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001385 }
Mike Stump11289f42009-09-09 15:08:12 +00001386
John McCall90d1c2d2009-09-24 23:30:46 +00001387 ConstantArrayType *New = new(*this,TypeAlignment)
1388 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001389 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001390 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001391 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001392}
1393
Steve Naroffcadebd02007-08-30 18:14:25 +00001394/// getVariableArrayType - Returns a non-unique reference to the type for a
1395/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001396QualType ASTContext::getVariableArrayType(QualType EltTy,
1397 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001398 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001399 unsigned EltTypeQuals,
1400 SourceRange Brackets) {
Eli Friedmanbd258282008-02-15 18:16:39 +00001401 // Since we don't unique expressions, it isn't possible to unique VLA's
1402 // that have an expression provided for their size.
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001403 QualType CanonType;
1404
1405 if (!EltTy.isCanonical()) {
1406 if (NumElts)
1407 NumElts->Retain();
1408 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1409 EltTypeQuals, Brackets);
1410 }
1411
John McCall90d1c2d2009-09-24 23:30:46 +00001412 VariableArrayType *New = new(*this, TypeAlignment)
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001413 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001414
1415 VariableArrayTypes.push_back(New);
1416 Types.push_back(New);
1417 return QualType(New, 0);
1418}
1419
Douglas Gregor4619e432008-12-05 23:32:09 +00001420/// getDependentSizedArrayType - Returns a non-unique reference to
1421/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001422/// type.
Douglas Gregor04318252009-07-06 15:59:29 +00001423QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1424 Expr *NumElts,
Douglas Gregor4619e432008-12-05 23:32:09 +00001425 ArrayType::ArraySizeModifier ASM,
Douglas Gregor04318252009-07-06 15:59:29 +00001426 unsigned EltTypeQuals,
1427 SourceRange Brackets) {
Douglas Gregorad2956c2009-11-19 18:03:26 +00001428 assert((!NumElts || NumElts->isTypeDependent() ||
1429 NumElts->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001430 "Size must be type- or value-dependent!");
1431
Douglas Gregorf3f95522009-07-31 00:23:35 +00001432 void *InsertPos = 0;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001433 DependentSizedArrayType *Canon = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001434 llvm::FoldingSetNodeID ID;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001435
1436 if (NumElts) {
1437 // Dependently-sized array types that do not have a specified
1438 // number of elements will have their sizes deduced from an
1439 // initializer.
Douglas Gregorad2956c2009-11-19 18:03:26 +00001440 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1441 EltTypeQuals, NumElts);
1442
1443 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1444 }
1445
Douglas Gregorf3f95522009-07-31 00:23:35 +00001446 DependentSizedArrayType *New;
1447 if (Canon) {
1448 // We already have a canonical version of this array type; use it as
1449 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001450 New = new (*this, TypeAlignment)
1451 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1452 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001453 } else {
1454 QualType CanonEltTy = getCanonicalType(EltTy);
1455 if (CanonEltTy == EltTy) {
John McCall90d1c2d2009-09-24 23:30:46 +00001456 New = new (*this, TypeAlignment)
1457 DependentSizedArrayType(*this, EltTy, QualType(),
1458 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001459
Douglas Gregorc42075a2010-02-04 18:10:26 +00001460 if (NumElts) {
1461 DependentSizedArrayType *CanonCheck
1462 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1463 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1464 (void)CanonCheck;
Douglas Gregorad2956c2009-11-19 18:03:26 +00001465 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001466 }
Douglas Gregorf3f95522009-07-31 00:23:35 +00001467 } else {
1468 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1469 ASM, EltTypeQuals,
1470 SourceRange());
John McCall90d1c2d2009-09-24 23:30:46 +00001471 New = new (*this, TypeAlignment)
1472 DependentSizedArrayType(*this, EltTy, Canon,
1473 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorf3f95522009-07-31 00:23:35 +00001474 }
1475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
Douglas Gregor4619e432008-12-05 23:32:09 +00001477 Types.push_back(New);
1478 return QualType(New, 0);
1479}
1480
Eli Friedmanbd258282008-02-15 18:16:39 +00001481QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1482 ArrayType::ArraySizeModifier ASM,
1483 unsigned EltTypeQuals) {
1484 llvm::FoldingSetNodeID ID;
Chris Lattner780b46f2009-02-19 17:31:02 +00001485 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001486
1487 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001488 if (IncompleteArrayType *ATP =
Eli Friedmanbd258282008-02-15 18:16:39 +00001489 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1490 return QualType(ATP, 0);
1491
1492 // If the element type isn't canonical, this won't be a canonical type
1493 // either, so fill in the canonical type field.
1494 QualType Canonical;
1495
John McCallb692a092009-10-22 20:10:53 +00001496 if (!EltTy.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001497 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001498 ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001499
1500 // Get the new insert position for the node we care about.
1501 IncompleteArrayType *NewIP =
1502 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001503 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001504 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001505
John McCall90d1c2d2009-09-24 23:30:46 +00001506 IncompleteArrayType *New = new (*this, TypeAlignment)
1507 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001508
1509 IncompleteArrayTypes.InsertNode(New, InsertPos);
1510 Types.push_back(New);
1511 return QualType(New, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001512}
1513
Steve Naroff91fcddb2007-07-18 18:00:27 +00001514/// getVectorType - Return the unique reference to a vector type of
1515/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001516QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1517 bool IsAltiVec, bool IsPixel) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001518 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001519
Chris Lattner76a00cf2008-04-06 22:59:24 +00001520 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001521 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001522
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001523 // Check if we've already instantiated a vector of this type.
1524 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001525 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1526 IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001527 void *InsertPos = 0;
1528 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1529 return QualType(VTP, 0);
1530
1531 // If the element type isn't canonical, this won't be a canonical type either,
1532 // so fill in the canonical type field.
1533 QualType Canonical;
John Thompson22334602010-02-05 00:12:22 +00001534 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1535 Canonical = getVectorType(getCanonicalType(vecType),
1536 NumElts, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00001537
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001538 // Get the new insert position for the node we care about.
1539 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001540 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001541 }
John McCall90d1c2d2009-09-24 23:30:46 +00001542 VectorType *New = new (*this, TypeAlignment)
John Thompson22334602010-02-05 00:12:22 +00001543 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001544 VectorTypes.InsertNode(New, InsertPos);
1545 Types.push_back(New);
1546 return QualType(New, 0);
1547}
1548
Nate Begemance4d7fc2008-04-18 23:10:10 +00001549/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001550/// the specified element type and size. VectorType must be a built-in type.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001551QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff91fcddb2007-07-18 18:00:27 +00001552 BuiltinType *baseType;
Mike Stump11289f42009-09-09 15:08:12 +00001553
Chris Lattner76a00cf2008-04-06 22:59:24 +00001554 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemance4d7fc2008-04-18 23:10:10 +00001555 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump11289f42009-09-09 15:08:12 +00001556
Steve Naroff91fcddb2007-07-18 18:00:27 +00001557 // Check if we've already instantiated a vector of this type.
1558 llvm::FoldingSetNodeID ID;
John Thompson22334602010-02-05 00:12:22 +00001559 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001560 void *InsertPos = 0;
1561 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1562 return QualType(VTP, 0);
1563
1564 // If the element type isn't canonical, this won't be a canonical type either,
1565 // so fill in the canonical type field.
1566 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001567 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001568 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001569
Steve Naroff91fcddb2007-07-18 18:00:27 +00001570 // Get the new insert position for the node we care about.
1571 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001572 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001573 }
John McCall90d1c2d2009-09-24 23:30:46 +00001574 ExtVectorType *New = new (*this, TypeAlignment)
1575 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001576 VectorTypes.InsertNode(New, InsertPos);
1577 Types.push_back(New);
1578 return QualType(New, 0);
1579}
1580
Mike Stump11289f42009-09-09 15:08:12 +00001581QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor758a8692009-06-17 21:51:59 +00001582 Expr *SizeExpr,
1583 SourceLocation AttrLoc) {
Douglas Gregor352169a2009-07-31 03:54:25 +00001584 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001585 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001586 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001587
Douglas Gregor352169a2009-07-31 03:54:25 +00001588 void *InsertPos = 0;
1589 DependentSizedExtVectorType *Canon
1590 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1591 DependentSizedExtVectorType *New;
1592 if (Canon) {
1593 // We already have a canonical version of this array type; use it as
1594 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001595 New = new (*this, TypeAlignment)
1596 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1597 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001598 } else {
1599 QualType CanonVecTy = getCanonicalType(vecType);
1600 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001601 New = new (*this, TypeAlignment)
1602 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1603 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001604
1605 DependentSizedExtVectorType *CanonCheck
1606 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1607 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1608 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001609 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1610 } else {
1611 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1612 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001613 New = new (*this, TypeAlignment)
1614 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001615 }
1616 }
Mike Stump11289f42009-09-09 15:08:12 +00001617
Douglas Gregor758a8692009-06-17 21:51:59 +00001618 Types.push_back(New);
1619 return QualType(New, 0);
1620}
1621
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001622/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001623///
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001624QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1625 const FunctionType::ExtInfo &Info) {
1626 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001627 // Unique functions, to guarantee there is only one function of a particular
1628 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001629 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001630 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001631
Chris Lattner47955de2007-01-27 08:37:20 +00001632 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001633 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001634 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001635 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001636
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001637 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001638 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001639 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001640 Canonical =
1641 getFunctionNoProtoType(getCanonicalType(ResultTy),
1642 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001643
Chris Lattner47955de2007-01-27 08:37:20 +00001644 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001645 FunctionNoProtoType *NewIP =
1646 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001647 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001648 }
Mike Stump11289f42009-09-09 15:08:12 +00001649
John McCall90d1c2d2009-09-24 23:30:46 +00001650 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001651 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001652 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001653 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001654 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001655}
1656
1657/// getFunctionType - Return a normal function type with a typed argument
1658/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner465fa322008-10-05 17:34:18 +00001659QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis22c40fa2008-10-24 21:46:40 +00001660 unsigned NumArgs, bool isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001661 unsigned TypeQuals, bool hasExceptionSpec,
1662 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001663 const QualType *ExArray,
1664 const FunctionType::ExtInfo &Info) {
1665 const CallingConv CallConv= Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001666 // Unique functions, to guarantee there is only one function of a particular
1667 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001668 llvm::FoldingSetNodeID ID;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001669 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001670 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001671 NumExs, ExArray, Info);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001672
1673 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001674 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001675 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001676 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001677
1678 // Determine whether the type being created is already canonical or not.
John McCallfc93cf92009-10-22 22:37:11 +00001679 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001680 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001681 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001682 isCanonical = false;
1683
1684 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001685 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001686 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001687 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001688 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001689 CanonicalArgs.reserve(NumArgs);
1690 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001691 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001692
Chris Lattner76a00cf2008-04-06 22:59:24 +00001693 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001694 CanonicalArgs.data(), NumArgs,
Douglas Gregorf9bd4ec2009-08-05 19:03:35 +00001695 isVariadic, TypeQuals, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001696 false, 0, 0,
1697 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001698
Chris Lattnerfd4de792007-01-27 01:15:32 +00001699 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001700 FunctionProtoType *NewIP =
1701 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnere05f5342008-10-12 00:26:57 +00001702 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001703 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001704
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001705 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001706 // for two variable size arrays (for parameter and exception types) at the
1707 // end of them.
Mike Stump11289f42009-09-09 15:08:12 +00001708 FunctionProtoType *FTP =
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001709 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1710 NumArgs*sizeof(QualType) +
John McCall90d1c2d2009-09-24 23:30:46 +00001711 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001712 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001713 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001714 ExArray, NumExs, Canonical, Info);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001715 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001716 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001717 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001718}
Chris Lattneref51c202006-11-10 07:17:23 +00001719
John McCalle78aac42010-03-10 03:28:59 +00001720#ifndef NDEBUG
1721static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1722 if (!isa<CXXRecordDecl>(D)) return false;
1723 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1724 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1725 return true;
1726 if (RD->getDescribedClassTemplate() &&
1727 !isa<ClassTemplateSpecializationDecl>(RD))
1728 return true;
1729 return false;
1730}
1731#endif
1732
1733/// getInjectedClassNameType - Return the unique reference to the
1734/// injected class name type for the specified templated declaration.
1735QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1736 QualType TST) {
1737 assert(NeedsInjectedClassNameType(Decl));
1738 if (Decl->TypeForDecl) {
1739 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1740 } else if (CXXRecordDecl *PrevDecl
1741 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1742 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1743 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1744 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1745 } else {
John McCall2408e322010-04-27 00:57:59 +00001746 Decl->TypeForDecl =
1747 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCalle78aac42010-03-10 03:28:59 +00001748 Types.push_back(Decl->TypeForDecl);
1749 }
1750 return QualType(Decl->TypeForDecl, 0);
1751}
1752
Douglas Gregor83a586e2008-04-13 21:07:44 +00001753/// getTypeDeclType - Return the unique reference to the type for the
1754/// specified type declaration.
John McCall96f0b5f2010-03-10 06:48:02 +00001755QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001756 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001757 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001758
John McCall81e38502010-02-16 03:57:14 +00001759 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001760 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001761
John McCall96f0b5f2010-03-10 06:48:02 +00001762 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1763 "Template type parameter types are always available.");
1764
John McCall81e38502010-02-16 03:57:14 +00001765 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001766 assert(!Record->getPreviousDeclaration() &&
1767 "struct/union has previous declaration");
1768 assert(!NeedsInjectedClassNameType(Record));
1769 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001770 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001771 assert(!Enum->getPreviousDeclaration() &&
1772 "enum has previous declaration");
1773 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00001774 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00001775 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1776 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00001777 } else
John McCall96f0b5f2010-03-10 06:48:02 +00001778 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001779
John McCall96f0b5f2010-03-10 06:48:02 +00001780 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00001781 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00001782}
1783
Chris Lattner32d920b2007-01-26 02:01:53 +00001784/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00001785/// specified typename decl.
John McCall81e38502010-02-16 03:57:14 +00001786QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001787 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001788
Chris Lattner76a00cf2008-04-06 22:59:24 +00001789 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall90d1c2d2009-09-24 23:30:46 +00001790 Decl->TypeForDecl = new(*this, TypeAlignment)
1791 TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattnercceab1a2007-03-26 20:16:44 +00001792 Types.push_back(Decl->TypeForDecl);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001793 return QualType(Decl->TypeForDecl, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00001794}
1795
John McCallcebee162009-10-18 09:09:24 +00001796/// \brief Retrieve a substitution-result type.
1797QualType
1798ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1799 QualType Replacement) {
John McCallb692a092009-10-22 20:10:53 +00001800 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00001801 && "replacement types must always be canonical");
1802
1803 llvm::FoldingSetNodeID ID;
1804 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1805 void *InsertPos = 0;
1806 SubstTemplateTypeParmType *SubstParm
1807 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1808
1809 if (!SubstParm) {
1810 SubstParm = new (*this, TypeAlignment)
1811 SubstTemplateTypeParmType(Parm, Replacement);
1812 Types.push_back(SubstParm);
1813 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1814 }
1815
1816 return QualType(SubstParm, 0);
1817}
1818
Douglas Gregoreff93e02009-02-05 23:33:38 +00001819/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00001820/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00001821/// name.
Mike Stump11289f42009-09-09 15:08:12 +00001822QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00001823 bool ParameterPack,
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001824 IdentifierInfo *Name) {
Douglas Gregoreff93e02009-02-05 23:33:38 +00001825 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001826 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001827 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001828 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00001829 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1830
1831 if (TypeParm)
1832 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001833
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001834 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00001835 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00001836 TypeParm = new (*this, TypeAlignment)
1837 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001838
1839 TemplateTypeParmType *TypeCheck
1840 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1841 assert(!TypeCheck && "Template type parameter canonical type broken");
1842 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00001843 } else
John McCall90d1c2d2009-09-24 23:30:46 +00001844 TypeParm = new (*this, TypeAlignment)
1845 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00001846
1847 Types.push_back(TypeParm);
1848 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1849
1850 return QualType(TypeParm, 0);
1851}
1852
John McCalle78aac42010-03-10 03:28:59 +00001853TypeSourceInfo *
1854ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1855 SourceLocation NameLoc,
1856 const TemplateArgumentListInfo &Args,
1857 QualType CanonType) {
1858 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1859
1860 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1861 TemplateSpecializationTypeLoc TL
1862 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1863 TL.setTemplateNameLoc(NameLoc);
1864 TL.setLAngleLoc(Args.getLAngleLoc());
1865 TL.setRAngleLoc(Args.getRAngleLoc());
1866 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1867 TL.setArgLocInfo(i, Args[i].getLocInfo());
1868 return DI;
1869}
1870
Mike Stump11289f42009-09-09 15:08:12 +00001871QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00001872ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00001873 const TemplateArgumentListInfo &Args,
John McCall30576cd2010-06-13 09:25:03 +00001874 QualType Canon) {
John McCall6b51f282009-11-23 01:53:49 +00001875 unsigned NumArgs = Args.size();
1876
John McCall0ad16662009-10-29 08:12:44 +00001877 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1878 ArgVec.reserve(NumArgs);
1879 for (unsigned i = 0; i != NumArgs; ++i)
1880 ArgVec.push_back(Args[i].getArgument());
1881
John McCall2408e322010-04-27 00:57:59 +00001882 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001883 Canon);
John McCall0ad16662009-10-29 08:12:44 +00001884}
1885
1886QualType
1887ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00001888 const TemplateArgument *Args,
1889 unsigned NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00001890 QualType Canon) {
Douglas Gregor15301382009-07-30 17:40:51 +00001891 if (!Canon.isNull())
1892 Canon = getCanonicalType(Canon);
1893 else {
1894 // Build the canonical template specialization type.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001895 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1896 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1897 CanonArgs.reserve(NumArgs);
1898 for (unsigned I = 0; I != NumArgs; ++I)
1899 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1900
1901 // Determine whether this canonical template specialization type already
1902 // exists.
1903 llvm::FoldingSetNodeID ID;
John McCall30576cd2010-06-13 09:25:03 +00001904 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor00044172009-07-29 16:09:57 +00001905 CanonArgs.data(), NumArgs, *this);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001906
1907 void *InsertPos = 0;
1908 TemplateSpecializationType *Spec
1909 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001910
Douglas Gregora8e02e72009-07-28 23:00:59 +00001911 if (!Spec) {
1912 // Allocate a new canonical template specialization type.
Mike Stump11289f42009-09-09 15:08:12 +00001913 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregora8e02e72009-07-28 23:00:59 +00001914 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001915 TypeAlignment);
John McCall30576cd2010-06-13 09:25:03 +00001916 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
Douglas Gregora8e02e72009-07-28 23:00:59 +00001917 CanonArgs.data(), NumArgs,
Douglas Gregor15301382009-07-30 17:40:51 +00001918 Canon);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001919 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001920 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregora8e02e72009-07-28 23:00:59 +00001921 }
Mike Stump11289f42009-09-09 15:08:12 +00001922
Douglas Gregor15301382009-07-30 17:40:51 +00001923 if (Canon.isNull())
1924 Canon = QualType(Spec, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001925 assert(Canon->isDependentType() &&
Douglas Gregora8e02e72009-07-28 23:00:59 +00001926 "Non-dependent template-id type must have a canonical type");
Douglas Gregor15301382009-07-30 17:40:51 +00001927 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00001928
Douglas Gregora8e02e72009-07-28 23:00:59 +00001929 // Allocate the (non-canonical) template specialization type, but don't
1930 // try to unique it: these types typically have location information that
1931 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00001932 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00001933 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00001934 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00001935 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00001936 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00001937 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00001938 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00001939
Douglas Gregor8bf42052009-02-09 18:46:07 +00001940 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00001941 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001942}
1943
Mike Stump11289f42009-09-09 15:08:12 +00001944QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00001945ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1946 NestedNameSpecifier *NNS,
1947 QualType NamedType) {
Douglas Gregor52537682009-03-19 00:18:19 +00001948 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001949 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00001950
1951 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00001952 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001953 if (T)
1954 return QualType(T, 0);
1955
Douglas Gregorc42075a2010-02-04 18:10:26 +00001956 QualType Canon = NamedType;
1957 if (!Canon.isCanonical()) {
1958 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001959 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1960 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00001961 (void)CheckT;
1962 }
1963
Abramo Bagnara6150c882010-05-11 21:36:43 +00001964 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00001965 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00001966 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00001967 return QualType(T, 0);
1968}
1969
Douglas Gregor02085352010-03-31 20:19:30 +00001970QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1971 NestedNameSpecifier *NNS,
1972 const IdentifierInfo *Name,
1973 QualType Canon) {
Douglas Gregor333489b2009-03-27 23:10:48 +00001974 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1975
1976 if (Canon.isNull()) {
1977 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00001978 ElaboratedTypeKeyword CanonKeyword = Keyword;
1979 if (Keyword == ETK_None)
1980 CanonKeyword = ETK_Typename;
1981
1982 if (CanonNNS != NNS || CanonKeyword != Keyword)
1983 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001984 }
1985
1986 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00001987 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00001988
1989 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001990 DependentNameType *T
1991 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00001992 if (T)
1993 return QualType(T, 0);
1994
Douglas Gregor02085352010-03-31 20:19:30 +00001995 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00001996 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001997 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001998 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00001999}
2000
Mike Stump11289f42009-09-09 15:08:12 +00002001QualType
John McCallc392f372010-06-11 00:33:02 +00002002ASTContext::getDependentTemplateSpecializationType(
2003 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002004 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002005 const IdentifierInfo *Name,
2006 const TemplateArgumentListInfo &Args) {
2007 // TODO: avoid this copy
2008 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2009 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2010 ArgCopy.push_back(Args[I].getArgument());
2011 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2012 ArgCopy.size(),
2013 ArgCopy.data());
2014}
2015
2016QualType
2017ASTContext::getDependentTemplateSpecializationType(
2018 ElaboratedTypeKeyword Keyword,
2019 NestedNameSpecifier *NNS,
2020 const IdentifierInfo *Name,
2021 unsigned NumArgs,
2022 const TemplateArgument *Args) {
Douglas Gregordce2b622009-04-01 00:28:59 +00002023 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2024
Douglas Gregorc42075a2010-02-04 18:10:26 +00002025 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002026 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2027 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002028
2029 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002030 DependentTemplateSpecializationType *T
2031 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002032 if (T)
2033 return QualType(T, 0);
2034
John McCallc392f372010-06-11 00:33:02 +00002035 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002036
John McCallc392f372010-06-11 00:33:02 +00002037 ElaboratedTypeKeyword CanonKeyword = Keyword;
2038 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2039
2040 bool AnyNonCanonArgs = false;
2041 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2042 for (unsigned I = 0; I != NumArgs; ++I) {
2043 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2044 if (!CanonArgs[I].structurallyEquals(Args[I]))
2045 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002046 }
2047
John McCallc392f372010-06-11 00:33:02 +00002048 QualType Canon;
2049 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2050 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2051 Name, NumArgs,
2052 CanonArgs.data());
2053
2054 // Find the insert position again.
2055 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2056 }
2057
2058 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2059 sizeof(TemplateArgument) * NumArgs),
2060 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002061 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002062 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002063 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002064 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002065 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002066}
2067
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002068/// CmpProtocolNames - Comparison predicate for sorting protocols
2069/// alphabetically.
2070static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2071 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002072 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002073}
2074
John McCall8b07ec22010-05-15 11:32:37 +00002075static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002076 unsigned NumProtocols) {
2077 if (NumProtocols == 0) return true;
2078
2079 for (unsigned i = 1; i != NumProtocols; ++i)
2080 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2081 return false;
2082 return true;
2083}
2084
2085static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002086 unsigned &NumProtocols) {
2087 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002088
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002089 // Sort protocols, keyed by name.
2090 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2091
2092 // Remove duplicates.
2093 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2094 NumProtocols = ProtocolsEnd-Protocols;
2095}
2096
John McCall8b07ec22010-05-15 11:32:37 +00002097QualType ASTContext::getObjCObjectType(QualType BaseType,
2098 ObjCProtocolDecl * const *Protocols,
2099 unsigned NumProtocols) {
2100 // If the base type is an interface and there aren't any protocols
2101 // to add, then the interface type will do just fine.
2102 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2103 return BaseType;
2104
2105 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002106 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002107 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002108 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002109 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2110 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002111
John McCall8b07ec22010-05-15 11:32:37 +00002112 // Build the canonical type, which has the canonical base type and
2113 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002114 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002115 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2116 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2117 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002118 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2119 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002120 unsigned UniqueCount = NumProtocols;
2121
John McCallfc93cf92009-10-22 22:37:11 +00002122 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002123 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2124 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002125 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002126 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2127 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002128 }
2129
2130 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002131 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2132 }
2133
2134 unsigned Size = sizeof(ObjCObjectTypeImpl);
2135 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2136 void *Mem = Allocate(Size, TypeAlignment);
2137 ObjCObjectTypeImpl *T =
2138 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2139
2140 Types.push_back(T);
2141 ObjCObjectTypes.InsertNode(T, InsertPos);
2142 return QualType(T, 0);
2143}
2144
2145/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2146/// the given object type.
2147QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2148 llvm::FoldingSetNodeID ID;
2149 ObjCObjectPointerType::Profile(ID, ObjectT);
2150
2151 void *InsertPos = 0;
2152 if (ObjCObjectPointerType *QT =
2153 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2154 return QualType(QT, 0);
2155
2156 // Find the canonical object type.
2157 QualType Canonical;
2158 if (!ObjectT.isCanonical()) {
2159 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2160
2161 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002162 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2163 }
2164
Douglas Gregorf85bee62010-02-08 22:59:26 +00002165 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002166 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2167 ObjCObjectPointerType *QType =
2168 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002169
Steve Narofffb4330f2009-06-17 22:40:22 +00002170 Types.push_back(QType);
2171 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002172 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002173}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002174
Steve Naroffc277ad12009-07-18 15:33:26 +00002175/// getObjCInterfaceType - Return the unique reference to the type for the
2176/// specified ObjC interface decl. The list of protocols is optional.
John McCall8b07ec22010-05-15 11:32:37 +00002177QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2178 if (Decl->TypeForDecl)
2179 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002180
John McCall8b07ec22010-05-15 11:32:37 +00002181 // FIXME: redeclarations?
2182 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2183 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2184 Decl->TypeForDecl = T;
2185 Types.push_back(T);
2186 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002187}
2188
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002189/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2190/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002191/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002192/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002193/// on canonical type's (which are always unique).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002194QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002195 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002196 if (tofExpr->isTypeDependent()) {
2197 llvm::FoldingSetNodeID ID;
2198 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002199
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002200 void *InsertPos = 0;
2201 DependentTypeOfExprType *Canon
2202 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2203 if (Canon) {
2204 // We already have a "canonical" version of an identical, dependent
2205 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002206 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002207 QualType((TypeOfExprType*)Canon, 0));
2208 }
2209 else {
2210 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002211 Canon
2212 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002213 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2214 toe = Canon;
2215 }
2216 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002217 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002218 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002219 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002220 Types.push_back(toe);
2221 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002222}
2223
Steve Naroffa773cd52007-08-01 18:02:17 +00002224/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2225/// TypeOfType AST's. The only motivation to unique these nodes would be
2226/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002227/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002228/// on canonical type's (which are always unique).
Steve Naroffad373bd2007-07-31 12:34:36 +00002229QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002230 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002231 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002232 Types.push_back(tot);
2233 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002234}
2235
Anders Carlssonad6bd352009-06-24 21:24:56 +00002236/// getDecltypeForExpr - Given an expr, will return the decltype for that
2237/// expression, according to the rules in C++0x [dcl.type.simple]p4
2238static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002239 if (e->isTypeDependent())
2240 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002241
Anders Carlssonad6bd352009-06-24 21:24:56 +00002242 // If e is an id expression or a class member access, decltype(e) is defined
2243 // as the type of the entity named by e.
2244 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2245 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2246 return VD->getType();
2247 }
2248 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2249 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2250 return FD->getType();
2251 }
2252 // If e is a function call or an invocation of an overloaded operator,
2253 // (parentheses around e are ignored), decltype(e) is defined as the
2254 // return type of that function.
2255 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2256 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002257
Anders Carlssonad6bd352009-06-24 21:24:56 +00002258 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002259
2260 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002261 // defined as T&, otherwise decltype(e) is defined as T.
2262 if (e->isLvalue(Context) == Expr::LV_Valid)
2263 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002264
Anders Carlssonad6bd352009-06-24 21:24:56 +00002265 return T;
2266}
2267
Anders Carlsson81df7b82009-06-24 19:06:50 +00002268/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2269/// DecltypeType AST's. The only motivation to unique these nodes would be
2270/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002271/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002272/// on canonical type's (which are always unique).
2273QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregorabd68132009-07-08 00:03:05 +00002274 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002275 if (e->isTypeDependent()) {
2276 llvm::FoldingSetNodeID ID;
2277 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002278
Douglas Gregora21f6c32009-07-30 23:36:40 +00002279 void *InsertPos = 0;
2280 DependentDecltypeType *Canon
2281 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2282 if (Canon) {
2283 // We already have a "canonical" version of an equivalent, dependent
2284 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002285 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002286 QualType((DecltypeType*)Canon, 0));
2287 }
2288 else {
2289 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002290 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002291 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2292 dt = Canon;
2293 }
2294 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002295 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002296 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002297 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002298 Types.push_back(dt);
2299 return QualType(dt, 0);
2300}
2301
Chris Lattnerfb072462007-01-23 05:45:31 +00002302/// getTagDeclType - Return the unique reference to the type for the
2303/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpb93185d2009-08-07 18:05:12 +00002304QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002305 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002306 // FIXME: What is the design on getTagDeclType when it requires casting
2307 // away const? mutable?
2308 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002309}
2310
Mike Stump11289f42009-09-09 15:08:12 +00002311/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2312/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2313/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002314CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002315 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002316}
Chris Lattnerfb072462007-01-23 05:45:31 +00002317
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002318/// getSignedWCharType - Return the type of "signed wchar_t".
2319/// Used when in C++, as a GCC extension.
2320QualType ASTContext::getSignedWCharType() const {
2321 // FIXME: derive from "Target" ?
2322 return WCharTy;
2323}
2324
2325/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2326/// Used when in C++, as a GCC extension.
2327QualType ASTContext::getUnsignedWCharType() const {
2328 // FIXME: derive from "Target" ?
2329 return UnsignedIntTy;
2330}
2331
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002332/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2333/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2334QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002335 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002336}
2337
Chris Lattnera21ad802008-04-02 05:18:44 +00002338//===----------------------------------------------------------------------===//
2339// Type Operators
2340//===----------------------------------------------------------------------===//
2341
John McCallfc93cf92009-10-22 22:37:11 +00002342CanQualType ASTContext::getCanonicalParamType(QualType T) {
2343 // Push qualifiers into arrays, and then discard any remaining
2344 // qualifiers.
2345 T = getCanonicalType(T);
2346 const Type *Ty = T.getTypePtr();
2347
2348 QualType Result;
2349 if (isa<ArrayType>(Ty)) {
2350 Result = getArrayDecayedType(QualType(Ty,0));
2351 } else if (isa<FunctionType>(Ty)) {
2352 Result = getPointerType(QualType(Ty, 0));
2353 } else {
2354 Result = QualType(Ty, 0);
2355 }
2356
2357 return CanQualType::CreateUnsafe(Result);
2358}
2359
Chris Lattnered0d0792008-04-06 22:41:35 +00002360/// getCanonicalType - Return the canonical (structural) type corresponding to
2361/// the specified potentially non-canonical type. The non-canonical version
2362/// of a type may have many "decorated" versions of types. Decorators can
2363/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2364/// to be free of any of these, allowing two canonical types to be compared
2365/// for exact equality with a simple pointer comparison.
Douglas Gregor2211d342009-08-05 05:36:45 +00002366CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall8ccfcb52009-09-24 19:53:00 +00002367 QualifierCollector Quals;
2368 const Type *Ptr = Quals.strip(T);
2369 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump11289f42009-09-09 15:08:12 +00002370
John McCall8ccfcb52009-09-24 19:53:00 +00002371 // The canonical internal type will be the canonical type *except*
2372 // that we push type qualifiers down through array types.
2373
2374 // If there are no new qualifiers to push down, stop here.
2375 if (!Quals.hasQualifiers())
Douglas Gregor2211d342009-08-05 05:36:45 +00002376 return CanQualType::CreateUnsafe(CanType);
Chris Lattner7adf0762008-08-04 07:31:14 +00002377
John McCall8ccfcb52009-09-24 19:53:00 +00002378 // If the type qualifiers are on an array type, get the canonical
2379 // type of the array with the qualifiers applied to the element
2380 // type.
Chris Lattner7adf0762008-08-04 07:31:14 +00002381 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2382 if (!AT)
John McCall8ccfcb52009-09-24 19:53:00 +00002383 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump11289f42009-09-09 15:08:12 +00002384
Chris Lattner7adf0762008-08-04 07:31:14 +00002385 // Get the canonical version of the element with the extra qualifiers on it.
2386 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002387 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattner7adf0762008-08-04 07:31:14 +00002388 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump11289f42009-09-09 15:08:12 +00002389
Chris Lattner7adf0762008-08-04 07:31:14 +00002390 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002391 return CanQualType::CreateUnsafe(
2392 getConstantArrayType(NewEltTy, CAT->getSize(),
2393 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002394 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002395 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002396 return CanQualType::CreateUnsafe(
2397 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002398 IAT->getIndexTypeCVRQualifiers()));
Mike Stump11289f42009-09-09 15:08:12 +00002399
Douglas Gregor4619e432008-12-05 23:32:09 +00002400 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor2211d342009-08-05 05:36:45 +00002401 return CanQualType::CreateUnsafe(
2402 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002403 DSAT->getSizeExpr() ?
2404 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002405 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002406 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor326b2fa2009-10-30 22:56:57 +00002407 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor4619e432008-12-05 23:32:09 +00002408
Chris Lattner7adf0762008-08-04 07:31:14 +00002409 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor2211d342009-08-05 05:36:45 +00002410 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002411 VAT->getSizeExpr() ?
2412 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor2211d342009-08-05 05:36:45 +00002413 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002414 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor2211d342009-08-05 05:36:45 +00002415 VAT->getBracketsRange()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002416}
2417
Chandler Carruth607f38e2009-12-29 07:16:59 +00002418QualType ASTContext::getUnqualifiedArrayType(QualType T,
2419 Qualifiers &Quals) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002420 Quals = T.getQualifiers();
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002421 const ArrayType *AT = getAsArrayType(T);
2422 if (!AT) {
Chandler Carruth04bdce62010-01-12 20:32:25 +00002423 return T.getUnqualifiedType();
Chandler Carruth607f38e2009-12-29 07:16:59 +00002424 }
2425
Chandler Carruth607f38e2009-12-29 07:16:59 +00002426 QualType Elt = AT->getElementType();
Zhongxing Xucd321a32010-01-05 08:15:06 +00002427 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002428 if (Elt == UnqualElt)
2429 return T;
2430
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002431 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002432 return getConstantArrayType(UnqualElt, CAT->getSize(),
2433 CAT->getSizeModifier(), 0);
2434 }
2435
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002436 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Chandler Carruth607f38e2009-12-29 07:16:59 +00002437 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2438 }
2439
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002440 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2441 return getVariableArrayType(UnqualElt,
2442 VAT->getSizeExpr() ?
2443 VAT->getSizeExpr()->Retain() : 0,
2444 VAT->getSizeModifier(),
2445 VAT->getIndexTypeCVRQualifiers(),
2446 VAT->getBracketsRange());
2447 }
2448
2449 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002450 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2451 DSAT->getSizeModifier(), 0,
2452 SourceRange());
2453}
2454
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002455/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2456/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2457/// they point to and return true. If T1 and T2 aren't pointer types
2458/// or pointer-to-member types, or if they are not similar at this
2459/// level, returns false and leaves T1 and T2 unchanged. Top-level
2460/// qualifiers on T1 and T2 are ignored. This function will typically
2461/// be called in a loop that successively "unwraps" pointer and
2462/// pointer-to-member types to compare them at each level.
2463bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2464 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2465 *T2PtrType = T2->getAs<PointerType>();
2466 if (T1PtrType && T2PtrType) {
2467 T1 = T1PtrType->getPointeeType();
2468 T2 = T2PtrType->getPointeeType();
2469 return true;
2470 }
2471
2472 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2473 *T2MPType = T2->getAs<MemberPointerType>();
2474 if (T1MPType && T2MPType &&
2475 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2476 QualType(T2MPType->getClass(), 0))) {
2477 T1 = T1MPType->getPointeeType();
2478 T2 = T2MPType->getPointeeType();
2479 return true;
2480 }
2481
2482 if (getLangOptions().ObjC1) {
2483 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2484 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2485 if (T1OPType && T2OPType) {
2486 T1 = T1OPType->getPointeeType();
2487 T2 = T2OPType->getPointeeType();
2488 return true;
2489 }
2490 }
2491
2492 // FIXME: Block pointers, too?
2493
2494 return false;
2495}
2496
John McCall847e2a12009-11-24 18:42:40 +00002497DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2498 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2499 return TD->getDeclName();
2500
2501 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2502 if (DTN->isIdentifier()) {
2503 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2504 } else {
2505 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2506 }
2507 }
2508
John McCalld28ae272009-12-02 08:04:21 +00002509 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2510 assert(Storage);
2511 return (*Storage->begin())->getDeclName();
John McCall847e2a12009-11-24 18:42:40 +00002512}
2513
Douglas Gregor6bc50582009-05-07 06:41:52 +00002514TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002515 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2516 if (TemplateTemplateParmDecl *TTP
2517 = dyn_cast<TemplateTemplateParmDecl>(Template))
2518 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2519
2520 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002521 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002522 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002523
John McCalld28ae272009-12-02 08:04:21 +00002524 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002525
Douglas Gregor6bc50582009-05-07 06:41:52 +00002526 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2527 assert(DTN && "Non-dependent template names must refer to template decls.");
2528 return DTN->CanonicalTemplateName;
2529}
2530
Douglas Gregoradee3e32009-11-11 23:06:43 +00002531bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2532 X = getCanonicalTemplateName(X);
2533 Y = getCanonicalTemplateName(Y);
2534 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2535}
2536
Mike Stump11289f42009-09-09 15:08:12 +00002537TemplateArgument
Douglas Gregora8e02e72009-07-28 23:00:59 +00002538ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2539 switch (Arg.getKind()) {
2540 case TemplateArgument::Null:
2541 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002542
Douglas Gregora8e02e72009-07-28 23:00:59 +00002543 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002544 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002545
Douglas Gregora8e02e72009-07-28 23:00:59 +00002546 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002547 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002548
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002549 case TemplateArgument::Template:
2550 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2551
Douglas Gregora8e02e72009-07-28 23:00:59 +00002552 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002553 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002554 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002555
Douglas Gregora8e02e72009-07-28 23:00:59 +00002556 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002557 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002558
Douglas Gregora8e02e72009-07-28 23:00:59 +00002559 case TemplateArgument::Pack: {
2560 // FIXME: Allocate in ASTContext
2561 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2562 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002563 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002564 AEnd = Arg.pack_end();
2565 A != AEnd; (void)++A, ++Idx)
2566 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002567
Douglas Gregora8e02e72009-07-28 23:00:59 +00002568 TemplateArgument Result;
2569 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2570 return Result;
2571 }
2572 }
2573
2574 // Silence GCC warning
2575 assert(false && "Unhandled template argument kind");
2576 return TemplateArgument();
2577}
2578
Douglas Gregor333489b2009-03-27 23:10:48 +00002579NestedNameSpecifier *
2580ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump11289f42009-09-09 15:08:12 +00002581 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002582 return 0;
2583
2584 switch (NNS->getKind()) {
2585 case NestedNameSpecifier::Identifier:
2586 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002587 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002588 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2589 NNS->getAsIdentifier());
2590
2591 case NestedNameSpecifier::Namespace:
2592 // A namespace is canonical; build a nested-name-specifier with
2593 // this namespace and no prefix.
2594 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2595
2596 case NestedNameSpecifier::TypeSpec:
2597 case NestedNameSpecifier::TypeSpecWithTemplate: {
2598 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump11289f42009-09-09 15:08:12 +00002599 return NestedNameSpecifier::Create(*this, 0,
2600 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregor333489b2009-03-27 23:10:48 +00002601 T.getTypePtr());
2602 }
2603
2604 case NestedNameSpecifier::Global:
2605 // The global specifier is canonical and unique.
2606 return NNS;
2607 }
2608
2609 // Required to silence a GCC warning
2610 return 0;
2611}
2612
Chris Lattner7adf0762008-08-04 07:31:14 +00002613
2614const ArrayType *ASTContext::getAsArrayType(QualType T) {
2615 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002616 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002617 // Handle the common positive case fast.
2618 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2619 return AT;
2620 }
Mike Stump11289f42009-09-09 15:08:12 +00002621
John McCall8ccfcb52009-09-24 19:53:00 +00002622 // Handle the common negative case fast.
Chris Lattner7adf0762008-08-04 07:31:14 +00002623 QualType CType = T->getCanonicalTypeInternal();
John McCall8ccfcb52009-09-24 19:53:00 +00002624 if (!isa<ArrayType>(CType))
Chris Lattner7adf0762008-08-04 07:31:14 +00002625 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002626
John McCall8ccfcb52009-09-24 19:53:00 +00002627 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00002628 // implements C99 6.7.3p8: "If the specification of an array type includes
2629 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00002630
Chris Lattner7adf0762008-08-04 07:31:14 +00002631 // If we get here, we either have type qualifiers on the type, or we have
2632 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00002633 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00002634
John McCall8ccfcb52009-09-24 19:53:00 +00002635 QualifierCollector Qs;
2636 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump11289f42009-09-09 15:08:12 +00002637
Chris Lattner7adf0762008-08-04 07:31:14 +00002638 // If we have a simple case, just return now.
2639 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall8ccfcb52009-09-24 19:53:00 +00002640 if (ATy == 0 || Qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00002641 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00002642
Chris Lattner7adf0762008-08-04 07:31:14 +00002643 // Otherwise, we have an array and we have qualifiers on it. Push the
2644 // qualifiers into the array element type and return a new array type.
2645 // Get the canonical version of the element with the extra qualifiers on it.
2646 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall8ccfcb52009-09-24 19:53:00 +00002647 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump11289f42009-09-09 15:08:12 +00002648
Chris Lattner7adf0762008-08-04 07:31:14 +00002649 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2650 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2651 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002652 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00002653 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2654 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2655 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002656 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00002657
Mike Stump11289f42009-09-09 15:08:12 +00002658 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00002659 = dyn_cast<DependentSizedArrayType>(ATy))
2660 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00002661 getDependentSizedArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002662 DSAT->getSizeExpr() ?
2663 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor4619e432008-12-05 23:32:09 +00002664 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002665 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002666 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00002667
Chris Lattner7adf0762008-08-04 07:31:14 +00002668 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00002669 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedman04fddf02009-08-15 02:50:32 +00002670 VAT->getSizeExpr() ?
John McCall8ccfcb52009-09-24 19:53:00 +00002671 VAT->getSizeExpr()->Retain() : 0,
Chris Lattner7adf0762008-08-04 07:31:14 +00002672 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00002673 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00002674 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00002675}
2676
2677
Chris Lattnera21ad802008-04-02 05:18:44 +00002678/// getArrayDecayedType - Return the properly qualified result of decaying the
2679/// specified array type to a pointer. This operation is non-trivial when
2680/// handling typedefs etc. The canonical type of "T" must be an array type,
2681/// this returns a pointer to a properly qualified element of the array.
2682///
2683/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2684QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattner7adf0762008-08-04 07:31:14 +00002685 // Get the element type with 'getAsArrayType' so that we don't lose any
2686 // typedefs in the element type of the array. This also handles propagation
2687 // of type qualifiers from the array type into the element type if present
2688 // (C99 6.7.3p8).
2689 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2690 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00002691
Chris Lattner7adf0762008-08-04 07:31:14 +00002692 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00002693
2694 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00002695 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00002696}
2697
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002698QualType ASTContext::getBaseElementType(QualType QT) {
John McCall8ccfcb52009-09-24 19:53:00 +00002699 QualifierCollector Qs;
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002700 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2701 QT = AT->getElementType();
2702 return Qs.apply(QT);
Douglas Gregor79f83ed2009-07-23 23:49:00 +00002703}
2704
Anders Carlsson4bf82142009-09-25 01:23:32 +00002705QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2706 QualType ElemTy = AT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002707
Anders Carlsson4bf82142009-09-25 01:23:32 +00002708 if (const ArrayType *AT = getAsArrayType(ElemTy))
2709 return getBaseElementType(AT);
Mike Stump11289f42009-09-09 15:08:12 +00002710
Anders Carlssone0808df2008-12-21 03:44:36 +00002711 return ElemTy;
2712}
2713
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002714/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00002715uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00002716ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2717 uint64_t ElementCount = 1;
2718 do {
2719 ElementCount *= CA->getSize().getZExtValue();
2720 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2721 } while (CA);
2722 return ElementCount;
2723}
2724
Steve Naroff0af91202007-04-27 21:51:21 +00002725/// getFloatingRank - Return a relative rank for floating point types.
2726/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002727static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00002728 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00002729 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00002730
John McCall9dd450b2009-09-21 23:43:11 +00002731 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2732 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00002733 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00002734 case BuiltinType::Float: return FloatRank;
2735 case BuiltinType::Double: return DoubleRank;
2736 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00002737 }
2738}
2739
Mike Stump11289f42009-09-09 15:08:12 +00002740/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2741/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00002742/// 'typeDomain' is a real floating point or complex type.
2743/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002744QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2745 QualType Domain) const {
2746 FloatingRank EltRank = getFloatingRank(Size);
2747 if (Domain->isComplexType()) {
2748 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00002749 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00002750 case FloatRank: return FloatComplexTy;
2751 case DoubleRank: return DoubleComplexTy;
2752 case LongDoubleRank: return LongDoubleComplexTy;
2753 }
Steve Naroff0af91202007-04-27 21:51:21 +00002754 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00002755
2756 assert(Domain->isRealFloatingType() && "Unknown domain!");
2757 switch (EltRank) {
2758 default: assert(0 && "getFloatingRank(): illegal value for rank");
2759 case FloatRank: return FloatTy;
2760 case DoubleRank: return DoubleTy;
2761 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00002762 }
Steve Naroffe4718892007-04-27 18:30:00 +00002763}
2764
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002765/// getFloatingTypeOrder - Compare the rank of the two specified floating
2766/// point types, ignoring the domain of the type (i.e. 'double' ==
2767/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002768/// LHS < RHS, return -1.
Chris Lattnerb90739d2008-04-06 23:38:49 +00002769int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2770 FloatingRank LHSR = getFloatingRank(LHS);
2771 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00002772
Chris Lattnerb90739d2008-04-06 23:38:49 +00002773 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002774 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00002775 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00002776 return 1;
2777 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00002778}
2779
Chris Lattner76a00cf2008-04-06 22:59:24 +00002780/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2781/// routine will assert if passed a built-in type that isn't an integer or enum,
2782/// or if it is not canonicalized.
Eli Friedman1efaaea2009-02-13 02:31:07 +00002783unsigned ASTContext::getIntegerRank(Type *T) {
John McCallb692a092009-10-22 20:10:53 +00002784 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedman1efaaea2009-02-13 02:31:07 +00002785 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00002786 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00002787
Eli Friedmanc131d3b2009-07-05 23:44:27 +00002788 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2789 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2790
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002791 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2792 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2793
2794 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2795 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2796
Chris Lattner76a00cf2008-04-06 22:59:24 +00002797 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002798 default: assert(0 && "getIntegerRank(): not a built-in integer");
2799 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002800 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002801 case BuiltinType::Char_S:
2802 case BuiltinType::Char_U:
2803 case BuiltinType::SChar:
2804 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002805 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002806 case BuiltinType::Short:
2807 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002808 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002809 case BuiltinType::Int:
2810 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002811 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002812 case BuiltinType::Long:
2813 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002814 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002815 case BuiltinType::LongLong:
2816 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00002817 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00002818 case BuiltinType::Int128:
2819 case BuiltinType::UInt128:
2820 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00002821 }
2822}
2823
Eli Friedman629ffb92009-08-20 04:21:42 +00002824/// \brief Whether this is a promotable bitfield reference according
2825/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2826///
2827/// \returns the type this bit-field will promote to, or NULL if no
2828/// promotion occurs.
2829QualType ASTContext::isPromotableBitField(Expr *E) {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00002830 if (E->isTypeDependent() || E->isValueDependent())
2831 return QualType();
2832
Eli Friedman629ffb92009-08-20 04:21:42 +00002833 FieldDecl *Field = E->getBitField();
2834 if (!Field)
2835 return QualType();
2836
2837 QualType FT = Field->getType();
2838
2839 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2840 uint64_t BitWidth = BitWidthAP.getZExtValue();
2841 uint64_t IntSize = getTypeSize(IntTy);
2842 // GCC extension compatibility: if the bit-field size is less than or equal
2843 // to the size of int, it gets promoted no matter what its type is.
2844 // For instance, unsigned long bf : 4 gets promoted to signed int.
2845 if (BitWidth < IntSize)
2846 return IntTy;
2847
2848 if (BitWidth == IntSize)
2849 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2850
2851 // Types bigger than int are not subject to promotions, and therefore act
2852 // like the base type.
2853 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2854 // is ridiculous.
2855 return QualType();
2856}
2857
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002858/// getPromotedIntegerType - Returns the type that Promotable will
2859/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2860/// integer type.
2861QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2862 assert(!Promotable.isNull());
2863 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00002864 if (const EnumType *ET = Promotable->getAs<EnumType>())
2865 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00002866 if (Promotable->isSignedIntegerType())
2867 return IntTy;
2868 uint64_t PromotableSize = getTypeSize(Promotable);
2869 uint64_t IntSize = getTypeSize(IntTy);
2870 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2871 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2872}
2873
Mike Stump11289f42009-09-09 15:08:12 +00002874/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002875/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00002876/// LHS < RHS, return -1.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002877int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002878 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2879 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002880 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002881
Chris Lattner76a00cf2008-04-06 22:59:24 +00002882 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2883 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00002884
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002885 unsigned LHSRank = getIntegerRank(LHSC);
2886 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00002887
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002888 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2889 if (LHSRank == RHSRank) return 0;
2890 return LHSRank > RHSRank ? 1 : -1;
2891 }
Mike Stump11289f42009-09-09 15:08:12 +00002892
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002893 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2894 if (LHSUnsigned) {
2895 // If the unsigned [LHS] type is larger, return it.
2896 if (LHSRank >= RHSRank)
2897 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00002898
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002899 // If the signed type can represent all values of the unsigned type, it
2900 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002901 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002902 return -1;
2903 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00002904
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002905 // If the unsigned [RHS] type is larger, return it.
2906 if (RHSRank >= LHSRank)
2907 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00002908
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002909 // If the signed type can represent all values of the unsigned type, it
2910 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00002911 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00002912 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00002913}
Anders Carlsson98f07902007-08-17 05:31:46 +00002914
Anders Carlsson6d417272009-11-14 21:45:58 +00002915static RecordDecl *
2916CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2917 SourceLocation L, IdentifierInfo *Id) {
2918 if (Ctx.getLangOptions().CPlusPlus)
2919 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2920 else
2921 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2922}
2923
Mike Stump11289f42009-09-09 15:08:12 +00002924// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson98f07902007-08-17 05:31:46 +00002925QualType ASTContext::getCFConstantStringType() {
2926 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002927 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002928 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00002929 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00002930 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00002931
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002932 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002933
Anders Carlsson98f07902007-08-17 05:31:46 +00002934 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00002935 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00002936 // int flags;
2937 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00002938 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00002939 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00002940 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002941 FieldTypes[3] = LongTy;
2942
Anders Carlsson98f07902007-08-17 05:31:46 +00002943 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002944 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002945 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002946 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00002947 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00002948 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002949 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002950 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002951 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00002952 }
2953
Douglas Gregord5058122010-02-11 01:19:42 +00002954 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00002955 }
Mike Stump11289f42009-09-09 15:08:12 +00002956
Anders Carlsson98f07902007-08-17 05:31:46 +00002957 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00002958}
Anders Carlsson87c149b2007-10-11 01:00:40 +00002959
Douglas Gregor512b0772009-04-23 22:29:11 +00002960void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002961 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00002962 assert(Rec && "Invalid CFConstantStringType");
2963 CFConstantStringTypeDecl = Rec->getDecl();
2964}
2965
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002966// getNSConstantStringType - Return the type used for constant NSStrings.
2967QualType ASTContext::getNSConstantStringType() {
2968 if (!NSConstantStringTypeDecl) {
2969 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00002970 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002971 &Idents.get("__builtin_NSString"));
2972 NSConstantStringTypeDecl->startDefinition();
2973
2974 QualType FieldTypes[3];
2975
2976 // const int *isa;
2977 FieldTypes[0] = getPointerType(IntTy.withConst());
2978 // const char *str;
2979 FieldTypes[1] = getPointerType(CharTy.withConst());
2980 // unsigned int length;
2981 FieldTypes[2] = UnsignedIntTy;
2982
2983 // Create fields
2984 for (unsigned i = 0; i < 3; ++i) {
2985 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2986 SourceLocation(), 0,
2987 FieldTypes[i], /*TInfo=*/0,
2988 /*BitWidth=*/0,
2989 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00002990 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002991 NSConstantStringTypeDecl->addDecl(Field);
2992 }
2993
2994 NSConstantStringTypeDecl->completeDefinition();
2995 }
2996
2997 return getTagDeclType(NSConstantStringTypeDecl);
2998}
2999
3000void ASTContext::setNSConstantStringType(QualType T) {
3001 const RecordType *Rec = T->getAs<RecordType>();
3002 assert(Rec && "Invalid NSConstantStringType");
3003 NSConstantStringTypeDecl = Rec->getDecl();
3004}
3005
Mike Stump11289f42009-09-09 15:08:12 +00003006QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003007 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003008 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003009 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003010 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003011 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003012
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003013 QualType FieldTypes[] = {
3014 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003015 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003016 getPointerType(UnsignedLongTy),
3017 getConstantArrayType(UnsignedLongTy,
3018 llvm::APInt(32, 5), ArrayType::Normal, 0)
3019 };
Mike Stump11289f42009-09-09 15:08:12 +00003020
Douglas Gregor91f84212008-12-11 16:49:14 +00003021 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003022 FieldDecl *Field = FieldDecl::Create(*this,
3023 ObjCFastEnumerationStateTypeDecl,
3024 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003025 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003026 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003027 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003028 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003029 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003030 }
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003031 if (getLangOptions().CPlusPlus)
Fariborz Jahanianc77f0f32010-05-27 16:35:00 +00003032 if (CXXRecordDecl *CXXRD =
3033 dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
Fariborz Jahanian9ea58392010-05-27 16:05:06 +00003034 CXXRD->setEmpty(false);
Mike Stump11289f42009-09-09 15:08:12 +00003035
Douglas Gregord5058122010-02-11 01:19:42 +00003036 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003037 }
Mike Stump11289f42009-09-09 15:08:12 +00003038
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003039 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3040}
3041
Mike Stumpd0153282009-10-20 02:12:22 +00003042QualType ASTContext::getBlockDescriptorType() {
3043 if (BlockDescriptorType)
3044 return getTagDeclType(BlockDescriptorType);
3045
3046 RecordDecl *T;
3047 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003048 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003049 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003050 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003051
3052 QualType FieldTypes[] = {
3053 UnsignedLongTy,
3054 UnsignedLongTy,
3055 };
3056
3057 const char *FieldNames[] = {
3058 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003059 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003060 };
3061
3062 for (size_t i = 0; i < 2; ++i) {
3063 FieldDecl *Field = FieldDecl::Create(*this,
3064 T,
3065 SourceLocation(),
3066 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003067 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003068 /*BitWidth=*/0,
3069 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003070 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003071 T->addDecl(Field);
3072 }
3073
Douglas Gregord5058122010-02-11 01:19:42 +00003074 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003075
3076 BlockDescriptorType = T;
3077
3078 return getTagDeclType(BlockDescriptorType);
3079}
3080
3081void ASTContext::setBlockDescriptorType(QualType T) {
3082 const RecordType *Rec = T->getAs<RecordType>();
3083 assert(Rec && "Invalid BlockDescriptorType");
3084 BlockDescriptorType = Rec->getDecl();
3085}
3086
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003087QualType ASTContext::getBlockDescriptorExtendedType() {
3088 if (BlockDescriptorExtendedType)
3089 return getTagDeclType(BlockDescriptorExtendedType);
3090
3091 RecordDecl *T;
3092 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003093 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003094 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003095 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003096
3097 QualType FieldTypes[] = {
3098 UnsignedLongTy,
3099 UnsignedLongTy,
3100 getPointerType(VoidPtrTy),
3101 getPointerType(VoidPtrTy)
3102 };
3103
3104 const char *FieldNames[] = {
3105 "reserved",
3106 "Size",
3107 "CopyFuncPtr",
3108 "DestroyFuncPtr"
3109 };
3110
3111 for (size_t i = 0; i < 4; ++i) {
3112 FieldDecl *Field = FieldDecl::Create(*this,
3113 T,
3114 SourceLocation(),
3115 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003116 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003117 /*BitWidth=*/0,
3118 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003119 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003120 T->addDecl(Field);
3121 }
3122
Douglas Gregord5058122010-02-11 01:19:42 +00003123 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003124
3125 BlockDescriptorExtendedType = T;
3126
3127 return getTagDeclType(BlockDescriptorExtendedType);
3128}
3129
3130void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3131 const RecordType *Rec = T->getAs<RecordType>();
3132 assert(Rec && "Invalid BlockDescriptorType");
3133 BlockDescriptorExtendedType = Rec->getDecl();
3134}
3135
Mike Stump94967902009-10-21 18:16:27 +00003136bool ASTContext::BlockRequiresCopying(QualType Ty) {
3137 if (Ty->isBlockPointerType())
3138 return true;
3139 if (isObjCNSObjectType(Ty))
3140 return true;
3141 if (Ty->isObjCObjectPointerType())
3142 return true;
3143 return false;
3144}
3145
3146QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3147 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003148 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003149 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003150 // unsigned int __flags;
3151 // unsigned int __size;
Mike Stump066b6162009-10-21 22:01:24 +00003152 // void *__copy_helper; // as needed
3153 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003154 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003155 // } *
3156
Mike Stump94967902009-10-21 18:16:27 +00003157 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3158
3159 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003160 llvm::SmallString<36> Name;
3161 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3162 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003163 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003164 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003165 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003166 T->startDefinition();
3167 QualType Int32Ty = IntTy;
3168 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3169 QualType FieldTypes[] = {
3170 getPointerType(VoidPtrTy),
3171 getPointerType(getTagDeclType(T)),
3172 Int32Ty,
3173 Int32Ty,
3174 getPointerType(VoidPtrTy),
3175 getPointerType(VoidPtrTy),
3176 Ty
3177 };
3178
3179 const char *FieldNames[] = {
3180 "__isa",
3181 "__forwarding",
3182 "__flags",
3183 "__size",
3184 "__copy_helper",
3185 "__destroy_helper",
3186 DeclName,
3187 };
3188
3189 for (size_t i = 0; i < 7; ++i) {
3190 if (!HasCopyAndDispose && i >=4 && i <= 5)
3191 continue;
3192 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3193 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003194 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003195 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003196 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003197 T->addDecl(Field);
3198 }
3199
Douglas Gregord5058122010-02-11 01:19:42 +00003200 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003201
3202 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003203}
3204
3205
3206QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003207 bool BlockHasCopyDispose,
John McCall87fe5d52010-05-20 01:18:31 +00003208 llvm::SmallVectorImpl<const Expr *> &Layout) {
3209
Mike Stumpd0153282009-10-20 02:12:22 +00003210 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003211 llvm::SmallString<36> Name;
3212 llvm::raw_svector_ostream(Name) << "__block_literal_"
3213 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003214 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003215 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003216 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003217 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003218 QualType FieldTypes[] = {
3219 getPointerType(VoidPtrTy),
3220 IntTy,
3221 IntTy,
3222 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003223 (BlockHasCopyDispose ?
3224 getPointerType(getBlockDescriptorExtendedType()) :
3225 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003226 };
3227
3228 const char *FieldNames[] = {
3229 "__isa",
3230 "__flags",
3231 "__reserved",
3232 "__FuncPtr",
3233 "__descriptor"
3234 };
3235
3236 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003237 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003238 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003239 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003240 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003241 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003242 T->addDecl(Field);
3243 }
3244
John McCall87fe5d52010-05-20 01:18:31 +00003245 for (unsigned i = 0; i < Layout.size(); ++i) {
3246 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003247
John McCall87fe5d52010-05-20 01:18:31 +00003248 QualType FieldType = E->getType();
3249 IdentifierInfo *FieldName = 0;
3250 if (isa<CXXThisExpr>(E)) {
3251 FieldName = &Idents.get("this");
3252 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3253 const ValueDecl *D = BDRE->getDecl();
3254 FieldName = D->getIdentifier();
3255 if (BDRE->isByRef())
3256 FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3257 } else {
3258 // Padding.
3259 assert(isa<ConstantArrayType>(FieldType) &&
3260 isa<DeclRefExpr>(E) &&
3261 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3262 "doesn't match characteristics of padding decl");
3263 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003264
3265 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003266 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003267 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003268 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003269 T->addDecl(Field);
3270 }
3271
Douglas Gregord5058122010-02-11 01:19:42 +00003272 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003273
3274 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003275}
3276
Douglas Gregor512b0772009-04-23 22:29:11 +00003277void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003278 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003279 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3280 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3281}
3282
Anders Carlsson18acd442007-10-29 06:33:42 +00003283// This returns true if a type has been typedefed to BOOL:
3284// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003285static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003286 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003287 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3288 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003289
Anders Carlssond8499822007-10-29 05:01:08 +00003290 return false;
3291}
3292
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003293/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003294/// purpose.
Ken Dyckde37a672010-01-11 19:19:56 +00003295CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck40775002010-01-11 17:06:35 +00003296 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003297
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003298 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003299 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003300 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003301 // Treat arrays as pointers, since that's how they're passed in.
3302 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003303 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003304 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003305}
3306
3307static inline
3308std::string charUnitsToString(const CharUnits &CU) {
3309 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003310}
3311
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003312/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003313/// declaration.
3314void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3315 std::string& S) {
3316 const BlockDecl *Decl = Expr->getBlockDecl();
3317 QualType BlockTy =
3318 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3319 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003320 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003321 // Compute size of all parameters.
3322 // Start with computing size of a pointer in number of bytes.
3323 // FIXME: There might(should) be a better way of doing this computation!
3324 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003325 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3326 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003327 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003328 E = Decl->param_end(); PI != E; ++PI) {
3329 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003330 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003331 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003332 ParmOffset += sz;
3333 }
3334 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003335 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003336 // Block pointer and offset.
3337 S += "@?0";
3338 ParmOffset = PtrSize;
3339
3340 // Argument types.
3341 ParmOffset = PtrSize;
3342 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3343 Decl->param_end(); PI != E; ++PI) {
3344 ParmVarDecl *PVDecl = *PI;
3345 QualType PType = PVDecl->getOriginalType();
3346 if (const ArrayType *AT =
3347 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3348 // Use array's original type only if it has known number of
3349 // elements.
3350 if (!isa<ConstantArrayType>(AT))
3351 PType = PVDecl->getType();
3352 } else if (PType->isFunctionType())
3353 PType = PVDecl->getType();
3354 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003355 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003356 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003357 }
3358}
3359
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003360/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003361/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003362void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003363 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003364 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003365 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003366 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003367 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003368 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003369 // Compute size of all parameters.
3370 // Start with computing size of a pointer in number of bytes.
3371 // FIXME: There might(should) be a better way of doing this computation!
3372 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003373 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003374 // The first two arguments (self and _cmd) are pointers; account for
3375 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003376 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003377 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003378 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003379 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003380 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003381 assert (sz.isPositive() &&
3382 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003383 ParmOffset += sz;
3384 }
Ken Dyck40775002010-01-11 17:06:35 +00003385 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003386 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003387 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003388
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003389 // Argument types.
3390 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003391 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003392 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003393 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003394 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003395 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003396 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3397 // Use array's original type only if it has known number of
3398 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003399 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003400 PType = PVDecl->getType();
3401 } else if (PType->isFunctionType())
3402 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003403 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003404 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003405 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003406 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003407 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003408 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003409 }
3410}
3411
Daniel Dunbar4932b362008-08-28 04:38:10 +00003412/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003413/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003414/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3415/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003416/// Property attributes are stored as a comma-delimited C string. The simple
3417/// attributes readonly and bycopy are encoded as single characters. The
3418/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3419/// encoded as single characters, followed by an identifier. Property types
3420/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003421/// these attributes are defined by the following enumeration:
3422/// @code
3423/// enum PropertyAttributes {
3424/// kPropertyReadOnly = 'R', // property is read-only.
3425/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3426/// kPropertyByref = '&', // property is a reference to the value last assigned
3427/// kPropertyDynamic = 'D', // property is dynamic
3428/// kPropertyGetter = 'G', // followed by getter selector name
3429/// kPropertySetter = 'S', // followed by setter selector name
3430/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3431/// kPropertyType = 't' // followed by old-style type encoding.
3432/// kPropertyWeak = 'W' // 'weak' property
3433/// kPropertyStrong = 'P' // property GC'able
3434/// kPropertyNonAtomic = 'N' // property non-atomic
3435/// };
3436/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003437void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003438 const Decl *Container,
Chris Lattner230fc3d2008-11-19 07:24:05 +00003439 std::string& S) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003440 // Collect information from the property implementation decl(s).
3441 bool Dynamic = false;
3442 ObjCPropertyImplDecl *SynthesizePID = 0;
3443
3444 // FIXME: Duplicated code due to poor abstraction.
3445 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003446 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003447 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3448 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003449 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003450 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003451 ObjCPropertyImplDecl *PID = *i;
3452 if (PID->getPropertyDecl() == PD) {
3453 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3454 Dynamic = true;
3455 } else {
3456 SynthesizePID = PID;
3457 }
3458 }
3459 }
3460 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003461 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003462 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003463 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003464 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003465 ObjCPropertyImplDecl *PID = *i;
3466 if (PID->getPropertyDecl() == PD) {
3467 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3468 Dynamic = true;
3469 } else {
3470 SynthesizePID = PID;
3471 }
3472 }
Mike Stump11289f42009-09-09 15:08:12 +00003473 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003474 }
3475 }
3476
3477 // FIXME: This is not very efficient.
3478 S = "T";
3479
3480 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003481 // GCC has some special rules regarding encoding of properties which
3482 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003483 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003484 true /* outermost type */,
3485 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003486
3487 if (PD->isReadOnly()) {
3488 S += ",R";
3489 } else {
3490 switch (PD->getSetterKind()) {
3491 case ObjCPropertyDecl::Assign: break;
3492 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003493 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003494 }
3495 }
3496
3497 // It really isn't clear at all what this means, since properties
3498 // are "dynamic by default".
3499 if (Dynamic)
3500 S += ",D";
3501
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003502 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3503 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003504
Daniel Dunbar4932b362008-08-28 04:38:10 +00003505 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3506 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003507 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003508 }
3509
3510 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3511 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003512 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003513 }
3514
3515 if (SynthesizePID) {
3516 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3517 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003518 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003519 }
3520
3521 // FIXME: OBJCGC: weak & strong
3522}
3523
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003524/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003525/// Another legacy compatibility encoding: 32-bit longs are encoded as
3526/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003527/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3528///
3529void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003530 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003531 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003532 if (BT->getKind() == BuiltinType::ULong &&
3533 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003534 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003535 else
Fariborz Jahanian77b6b5d2009-02-11 23:59:18 +00003536 if (BT->getKind() == BuiltinType::Long &&
3537 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003538 PointeeTy = IntTy;
3539 }
3540 }
3541}
3542
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003543void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003544 const FieldDecl *Field) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003545 // We follow the behavior of gcc, expanding structures which are
3546 // directly pointed to, and expanding embedded structures. Note that
3547 // these rules are sufficient to prevent recursive encoding of the
3548 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003549 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003550 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003551}
3552
David Chisnallb190a2c2010-06-04 01:10:52 +00003553static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3554 switch (T->getAs<BuiltinType>()->getKind()) {
3555 default: assert(0 && "Unhandled builtin type kind");
3556 case BuiltinType::Void: return 'v';
3557 case BuiltinType::Bool: return 'B';
3558 case BuiltinType::Char_U:
3559 case BuiltinType::UChar: return 'C';
3560 case BuiltinType::UShort: return 'S';
3561 case BuiltinType::UInt: return 'I';
3562 case BuiltinType::ULong:
3563 return
3564 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3565 case BuiltinType::UInt128: return 'T';
3566 case BuiltinType::ULongLong: return 'Q';
3567 case BuiltinType::Char_S:
3568 case BuiltinType::SChar: return 'c';
3569 case BuiltinType::Short: return 's';
John McCalldad856d2010-06-11 10:11:05 +00003570 case BuiltinType::WChar:
David Chisnallb190a2c2010-06-04 01:10:52 +00003571 case BuiltinType::Int: return 'i';
3572 case BuiltinType::Long:
3573 return
3574 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3575 case BuiltinType::LongLong: return 'q';
3576 case BuiltinType::Int128: return 't';
3577 case BuiltinType::Float: return 'f';
3578 case BuiltinType::Double: return 'd';
3579 case BuiltinType::LongDouble: return 'd';
3580 }
3581}
3582
Mike Stump11289f42009-09-09 15:08:12 +00003583static void EncodeBitField(const ASTContext *Context, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00003584 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003585 const Expr *E = FD->getBitWidth();
3586 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3587 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003588 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00003589 // The NeXT runtime encodes bit fields as b followed by the number of bits.
3590 // The GNU runtime requires more information; bitfields are encoded as b,
3591 // then the offset (in bits) of the first element, then the type of the
3592 // bitfield, then the size in bits. For example, in this structure:
3593 //
3594 // struct
3595 // {
3596 // int integer;
3597 // int flags:2;
3598 // };
3599 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3600 // runtime, but b32i2 for the GNU runtime. The reason for this extra
3601 // information is not especially sensible, but we're stuck with it for
3602 // compatibility with GCC, although providing it breaks anything that
3603 // actually uses runtime introspection and wants to work on both runtimes...
3604 if (!Ctx->getLangOptions().NeXTRuntime) {
3605 const RecordDecl *RD = FD->getParent();
3606 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3607 // FIXME: This same linear search is also used in ExprConstant - it might
3608 // be better if the FieldDecl stored its offset. We'd be increasing the
3609 // size of the object slightly, but saving some time every time it is used.
3610 unsigned i = 0;
3611 for (RecordDecl::field_iterator Field = RD->field_begin(),
3612 FieldEnd = RD->field_end();
3613 Field != FieldEnd; (void)++Field, ++i) {
3614 if (*Field == FD)
3615 break;
3616 }
3617 S += llvm::utostr(RL.getFieldOffset(i));
3618 S += ObjCEncodingForPrimitiveKind(Context, T);
3619 }
3620 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003621 S += llvm::utostr(N);
3622}
3623
Daniel Dunbar07d07852009-10-18 21:17:35 +00003624// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003625void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3626 bool ExpandPointedToStructures,
3627 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00003628 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003629 bool OutermostType,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00003630 bool EncodingProperty) {
David Chisnallb190a2c2010-06-04 01:10:52 +00003631 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003632 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003633 return EncodeBitField(this, S, T, FD);
3634 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003635 return;
3636 }
Mike Stump11289f42009-09-09 15:08:12 +00003637
John McCall9dd450b2009-09-21 23:43:11 +00003638 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00003639 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00003640 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00003641 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003642 return;
3643 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00003644
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003645 // encoding for pointer or r3eference types.
3646 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003647 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00003648 if (PT->isObjCSelType()) {
3649 S += ':';
3650 return;
3651 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003652 PointeeTy = PT->getPointeeType();
3653 }
3654 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3655 PointeeTy = RT->getPointeeType();
3656 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003657 bool isReadOnly = false;
3658 // For historical/compatibility reasons, the read-only qualifier of the
3659 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3660 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00003661 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00003662 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003663 if (OutermostType && T.isConstQualified()) {
3664 isReadOnly = true;
3665 S += 'r';
3666 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003667 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003668 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003669 while (P->getAs<PointerType>())
3670 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003671 if (P.isConstQualified()) {
3672 isReadOnly = true;
3673 S += 'r';
3674 }
3675 }
3676 if (isReadOnly) {
3677 // Another legacy compatibility encoding. Some ObjC qualifier and type
3678 // combinations need to be rearranged.
3679 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003680 if (llvm::StringRef(S).endswith("nr"))
3681 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003682 }
Mike Stump11289f42009-09-09 15:08:12 +00003683
Anders Carlssond8499822007-10-29 05:01:08 +00003684 if (PointeeTy->isCharType()) {
3685 // char pointer types should be encoded as '*' unless it is a
3686 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00003687 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00003688 S += '*';
3689 return;
3690 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003691 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00003692 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3693 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3694 S += '#';
3695 return;
3696 }
3697 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3698 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3699 S += '@';
3700 return;
3701 }
3702 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00003703 }
Anders Carlssond8499822007-10-29 05:01:08 +00003704 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003705 getLegacyIntegralTypeEncoding(PointeeTy);
3706
Mike Stump11289f42009-09-09 15:08:12 +00003707 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003708 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00003709 return;
3710 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00003711
Chris Lattnere7cabb92009-07-13 00:10:46 +00003712 if (const ArrayType *AT =
3713 // Ignore type qualifiers etc.
3714 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00003715 if (isa<IncompleteArrayType>(AT)) {
3716 // Incomplete arrays are encoded as a pointer to the array element.
3717 S += '^';
3718
Mike Stump11289f42009-09-09 15:08:12 +00003719 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003720 false, ExpandStructures, FD);
3721 } else {
3722 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00003723
Anders Carlssond05f44b2009-02-22 01:38:57 +00003724 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3725 S += llvm::utostr(CAT->getSize().getZExtValue());
3726 else {
3727 //Variable length arrays are encoded as a regular array with 0 elements.
3728 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3729 S += '0';
3730 }
Mike Stump11289f42009-09-09 15:08:12 +00003731
3732 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00003733 false, ExpandStructures, FD);
3734 S += ']';
3735 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003736 return;
3737 }
Mike Stump11289f42009-09-09 15:08:12 +00003738
John McCall9dd450b2009-09-21 23:43:11 +00003739 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00003740 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003741 return;
3742 }
Mike Stump11289f42009-09-09 15:08:12 +00003743
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003744 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003745 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003746 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00003747 // Anonymous structures print as '?'
3748 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3749 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00003750 if (ClassTemplateSpecializationDecl *Spec
3751 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3752 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3753 std::string TemplateArgsStr
3754 = TemplateSpecializationType::PrintTemplateArgumentList(
3755 TemplateArgs.getFlatArgumentList(),
3756 TemplateArgs.flat_size(),
3757 (*this).PrintingPolicy);
3758
3759 S += TemplateArgsStr;
3760 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00003761 } else {
3762 S += '?';
3763 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003764 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003765 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003766 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3767 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00003768 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003769 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003770 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00003771 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003772 S += '"';
3773 }
Mike Stump11289f42009-09-09 15:08:12 +00003774
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003775 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003776 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00003777 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003778 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003779 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003780 QualType qt = Field->getType();
3781 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00003782 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003783 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003784 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003785 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00003786 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00003787 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003788 return;
3789 }
Mike Stump11289f42009-09-09 15:08:12 +00003790
Chris Lattnere7cabb92009-07-13 00:10:46 +00003791 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003792 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00003793 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00003794 else
3795 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003796 return;
3797 }
Mike Stump11289f42009-09-09 15:08:12 +00003798
Chris Lattnere7cabb92009-07-13 00:10:46 +00003799 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00003800 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00003801 return;
3802 }
Mike Stump11289f42009-09-09 15:08:12 +00003803
John McCall8b07ec22010-05-15 11:32:37 +00003804 // Ignore protocol qualifiers when mangling at this level.
3805 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3806 T = OT->getBaseType();
3807
John McCall8ccfcb52009-09-24 19:53:00 +00003808 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003809 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00003810 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003811 S += '{';
3812 const IdentifierInfo *II = OI->getIdentifier();
3813 S += II->getName();
3814 S += '=';
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003815 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003816 CollectObjCIvars(OI, RecFields);
Chris Lattner5b36ddb2009-03-31 08:48:01 +00003817 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003818 if (RecFields[i]->isBitField())
Mike Stump11289f42009-09-09 15:08:12 +00003819 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003820 RecFields[i]);
3821 else
Mike Stump11289f42009-09-09 15:08:12 +00003822 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003823 FD);
3824 }
3825 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00003826 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00003827 }
Mike Stump11289f42009-09-09 15:08:12 +00003828
John McCall9dd450b2009-09-21 23:43:11 +00003829 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003830 if (OPT->isObjCIdType()) {
3831 S += '@';
3832 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003833 }
Mike Stump11289f42009-09-09 15:08:12 +00003834
Steve Narofff0c86112009-10-28 22:03:49 +00003835 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3836 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3837 // Since this is a binary compatibility issue, need to consult with runtime
3838 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003839 S += '#';
3840 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003841 }
Mike Stump11289f42009-09-09 15:08:12 +00003842
Chris Lattnere7cabb92009-07-13 00:10:46 +00003843 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003844 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00003845 ExpandPointedToStructures,
3846 ExpandStructures, FD);
3847 if (FD || EncodingProperty) {
3848 // Note that we do extended encoding of protocol qualifer list
3849 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003850 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00003851 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3852 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003853 S += '<';
3854 S += (*I)->getNameAsString();
3855 S += '>';
3856 }
3857 S += '"';
3858 }
3859 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00003860 }
Mike Stump11289f42009-09-09 15:08:12 +00003861
Chris Lattnere7cabb92009-07-13 00:10:46 +00003862 QualType PointeeTy = OPT->getPointeeType();
3863 if (!EncodingProperty &&
3864 isa<TypedefType>(PointeeTy.getTypePtr())) {
3865 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00003866 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00003867 // {...};
3868 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00003869 getObjCEncodingForTypeImpl(PointeeTy, S,
3870 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00003871 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003872 return;
3873 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003874
3875 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00003876 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003877 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00003878 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00003879 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3880 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00003881 S += '<';
3882 S += (*I)->getNameAsString();
3883 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00003884 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00003885 S += '"';
3886 }
3887 return;
3888 }
Mike Stump11289f42009-09-09 15:08:12 +00003889
John McCalla9e6e8d2010-05-17 23:56:34 +00003890 // gcc just blithely ignores member pointers.
3891 // TODO: maybe there should be a mangling for these
3892 if (T->getAs<MemberPointerType>())
3893 return;
3894
Chris Lattnere7cabb92009-07-13 00:10:46 +00003895 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00003896}
3897
Mike Stump11289f42009-09-09 15:08:12 +00003898void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003899 std::string& S) const {
3900 if (QT & Decl::OBJC_TQ_In)
3901 S += 'n';
3902 if (QT & Decl::OBJC_TQ_Inout)
3903 S += 'N';
3904 if (QT & Decl::OBJC_TQ_Out)
3905 S += 'o';
3906 if (QT & Decl::OBJC_TQ_Bycopy)
3907 S += 'O';
3908 if (QT & Decl::OBJC_TQ_Byref)
3909 S += 'R';
3910 if (QT & Decl::OBJC_TQ_Oneway)
3911 S += 'V';
3912}
3913
Chris Lattnere7cabb92009-07-13 00:10:46 +00003914void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00003915 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003916
Anders Carlsson87c149b2007-10-11 01:00:40 +00003917 BuiltinVaListType = T;
3918}
3919
Chris Lattnere7cabb92009-07-13 00:10:46 +00003920void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003921 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00003922}
3923
Chris Lattnere7cabb92009-07-13 00:10:46 +00003924void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00003925 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00003926}
3927
Chris Lattnere7cabb92009-07-13 00:10:46 +00003928void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003929 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00003930}
3931
Chris Lattnere7cabb92009-07-13 00:10:46 +00003932void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003933 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00003934}
3935
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003936void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00003937 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00003938 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00003939
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003940 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00003941}
3942
John McCalld28ae272009-12-02 08:04:21 +00003943/// \brief Retrieve the template name that corresponds to a non-empty
3944/// lookup.
John McCallad371252010-01-20 00:46:10 +00003945TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3946 UnresolvedSetIterator End) {
John McCalld28ae272009-12-02 08:04:21 +00003947 unsigned size = End - Begin;
3948 assert(size > 1 && "set is not overloaded!");
3949
3950 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3951 size * sizeof(FunctionTemplateDecl*));
3952 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3953
3954 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00003955 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00003956 NamedDecl *D = *I;
3957 assert(isa<FunctionTemplateDecl>(D) ||
3958 (isa<UsingShadowDecl>(D) &&
3959 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3960 *Storage++ = D;
3961 }
3962
3963 return TemplateName(OT);
3964}
3965
Douglas Gregordc572a32009-03-30 22:58:21 +00003966/// \brief Retrieve the template name that represents a qualified
3967/// template name such as \c std::vector.
Mike Stump11289f42009-09-09 15:08:12 +00003968TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003969 bool TemplateKeyword,
3970 TemplateDecl *Template) {
Douglas Gregorc42075a2010-02-04 18:10:26 +00003971 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00003972 llvm::FoldingSetNodeID ID;
3973 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3974
3975 void *InsertPos = 0;
3976 QualifiedTemplateName *QTN =
3977 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3978 if (!QTN) {
3979 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3980 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3981 }
3982
3983 return TemplateName(QTN);
3984}
3985
3986/// \brief Retrieve the template name that represents a dependent
3987/// template name such as \c MetaFun::template apply.
Mike Stump11289f42009-09-09 15:08:12 +00003988TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003989 const IdentifierInfo *Name) {
Mike Stump11289f42009-09-09 15:08:12 +00003990 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00003991 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00003992
3993 llvm::FoldingSetNodeID ID;
3994 DependentTemplateName::Profile(ID, NNS, Name);
3995
3996 void *InsertPos = 0;
3997 DependentTemplateName *QTN =
3998 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3999
4000 if (QTN)
4001 return TemplateName(QTN);
4002
4003 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4004 if (CanonNNS == NNS) {
4005 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4006 } else {
4007 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4008 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004009 DependentTemplateName *CheckQTN =
4010 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4011 assert(!CheckQTN && "Dependent type name canonicalization broken");
4012 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004013 }
4014
4015 DependentTemplateNames.InsertNode(QTN, InsertPos);
4016 return TemplateName(QTN);
4017}
4018
Douglas Gregor71395fa2009-11-04 00:56:37 +00004019/// \brief Retrieve the template name that represents a dependent
4020/// template name such as \c MetaFun::template operator+.
4021TemplateName
4022ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4023 OverloadedOperatorKind Operator) {
4024 assert((!NNS || NNS->isDependent()) &&
4025 "Nested name specifier must be dependent");
4026
4027 llvm::FoldingSetNodeID ID;
4028 DependentTemplateName::Profile(ID, NNS, Operator);
4029
4030 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004031 DependentTemplateName *QTN
4032 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004033
4034 if (QTN)
4035 return TemplateName(QTN);
4036
4037 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4038 if (CanonNNS == NNS) {
4039 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4040 } else {
4041 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4042 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004043
4044 DependentTemplateName *CheckQTN
4045 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4046 assert(!CheckQTN && "Dependent template name canonicalization broken");
4047 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004048 }
4049
4050 DependentTemplateNames.InsertNode(QTN, InsertPos);
4051 return TemplateName(QTN);
4052}
4053
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004054/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004055/// TargetInfo, produce the corresponding type. The unsigned @p Type
4056/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004057CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004058 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004059 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004060 case TargetInfo::SignedShort: return ShortTy;
4061 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4062 case TargetInfo::SignedInt: return IntTy;
4063 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4064 case TargetInfo::SignedLong: return LongTy;
4065 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4066 case TargetInfo::SignedLongLong: return LongLongTy;
4067 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4068 }
4069
4070 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004071 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004072}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004073
4074//===----------------------------------------------------------------------===//
4075// Type Predicates.
4076//===----------------------------------------------------------------------===//
4077
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004078/// isObjCNSObjectType - Return true if this is an NSObject object using
4079/// NSObject attribute on a c-style pointer type.
4080/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004081/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004082///
4083bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4084 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4085 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004086 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004087 return true;
4088 }
Mike Stump11289f42009-09-09 15:08:12 +00004089 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004090}
4091
Fariborz Jahanian96207692009-02-18 21:49:28 +00004092/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4093/// garbage collection attribute.
4094///
John McCall8ccfcb52009-09-24 19:53:00 +00004095Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4096 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004097 if (getLangOptions().ObjC1 &&
4098 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerd60183d2009-02-18 22:53:11 +00004099 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian96207692009-02-18 21:49:28 +00004100 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump11289f42009-09-09 15:08:12 +00004101 // (or pointers to them) be treated as though they were declared
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004102 // as __strong.
John McCall8ccfcb52009-09-24 19:53:00 +00004103 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian8d6298b2009-09-10 23:38:45 +00004104 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004105 GCAttrs = Qualifiers::Strong;
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004106 else if (Ty->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004107 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahanian0f466c72009-02-19 23:36:06 +00004108 }
Fariborz Jahaniand381cde2009-04-11 00:00:54 +00004109 // Non-pointers have none gc'able attribute regardless of the attribute
4110 // set on them.
Steve Naroff79d12152009-07-16 15:41:00 +00004111 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall8ccfcb52009-09-24 19:53:00 +00004112 return Qualifiers::GCNone;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004113 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004114 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004115}
4116
Chris Lattner49af6a42008-04-07 06:51:04 +00004117//===----------------------------------------------------------------------===//
4118// Type Compatibility Testing
4119//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004120
Mike Stump11289f42009-09-09 15:08:12 +00004121/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004122/// compatible.
4123static bool areCompatVectorTypes(const VectorType *LHS,
4124 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004125 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004126 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004127 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004128}
4129
Steve Naroff8e6aee52009-07-23 01:01:38 +00004130//===----------------------------------------------------------------------===//
4131// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4132//===----------------------------------------------------------------------===//
4133
4134/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4135/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004136bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4137 ObjCProtocolDecl *rProto) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004138 if (lProto == rProto)
4139 return true;
4140 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4141 E = rProto->protocol_end(); PI != E; ++PI)
4142 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4143 return true;
4144 return false;
4145}
4146
Steve Naroff8e6aee52009-07-23 01:01:38 +00004147/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4148/// return true if lhs's protocols conform to rhs's protocol; false
4149/// otherwise.
4150bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4151 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4152 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4153 return false;
4154}
4155
4156/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4157/// ObjCQualifiedIDType.
4158bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4159 bool compare) {
4160 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004161 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004162 lhs->isObjCIdType() || lhs->isObjCClassType())
4163 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004164 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004165 rhs->isObjCIdType() || rhs->isObjCClassType())
4166 return true;
4167
4168 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004169 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004170
Steve Naroff8e6aee52009-07-23 01:01:38 +00004171 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004172
Steve Naroff8e6aee52009-07-23 01:01:38 +00004173 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004174 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004175 // make sure we check the class hierarchy.
4176 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4177 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4178 E = lhsQID->qual_end(); I != E; ++I) {
4179 // when comparing an id<P> on lhs with a static type on rhs,
4180 // see if static class implements all of id's protocols, directly or
4181 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004182 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004183 return false;
4184 }
4185 }
4186 // If there are no qualifiers and no interface, we have an 'id'.
4187 return true;
4188 }
Mike Stump11289f42009-09-09 15:08:12 +00004189 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004190 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4191 E = lhsQID->qual_end(); I != E; ++I) {
4192 ObjCProtocolDecl *lhsProto = *I;
4193 bool match = false;
4194
4195 // when comparing an id<P> on lhs with a static type on rhs,
4196 // see if static class implements all of id's protocols, directly or
4197 // through its super class and categories.
4198 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4199 E = rhsOPT->qual_end(); J != E; ++J) {
4200 ObjCProtocolDecl *rhsProto = *J;
4201 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4202 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4203 match = true;
4204 break;
4205 }
4206 }
Mike Stump11289f42009-09-09 15:08:12 +00004207 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004208 // make sure we check the class hierarchy.
4209 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4210 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4211 E = lhsQID->qual_end(); I != E; ++I) {
4212 // when comparing an id<P> on lhs with a static type on rhs,
4213 // see if static class implements all of id's protocols, directly or
4214 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004215 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004216 match = true;
4217 break;
4218 }
4219 }
4220 }
4221 if (!match)
4222 return false;
4223 }
Mike Stump11289f42009-09-09 15:08:12 +00004224
Steve Naroff8e6aee52009-07-23 01:01:38 +00004225 return true;
4226 }
Mike Stump11289f42009-09-09 15:08:12 +00004227
Steve Naroff8e6aee52009-07-23 01:01:38 +00004228 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4229 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4230
Mike Stump11289f42009-09-09 15:08:12 +00004231 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004232 lhs->getAsObjCInterfacePointerType()) {
4233 if (lhsOPT->qual_empty()) {
4234 bool match = false;
4235 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4236 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4237 E = rhsQID->qual_end(); I != E; ++I) {
4238 // when comparing an id<P> on lhs with a static type on rhs,
4239 // see if static class implements all of id's protocols, directly or
4240 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004241 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004242 match = true;
4243 break;
4244 }
4245 }
4246 if (!match)
4247 return false;
4248 }
4249 return true;
4250 }
Mike Stump11289f42009-09-09 15:08:12 +00004251 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004252 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4253 E = lhsOPT->qual_end(); I != E; ++I) {
4254 ObjCProtocolDecl *lhsProto = *I;
4255 bool match = false;
4256
4257 // when comparing an id<P> on lhs with a static type on rhs,
4258 // see if static class implements all of id's protocols, directly or
4259 // through its super class and categories.
4260 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4261 E = rhsQID->qual_end(); J != E; ++J) {
4262 ObjCProtocolDecl *rhsProto = *J;
4263 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4264 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4265 match = true;
4266 break;
4267 }
4268 }
4269 if (!match)
4270 return false;
4271 }
4272 return true;
4273 }
4274 return false;
4275}
4276
Eli Friedman47f77112008-08-22 00:56:42 +00004277/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004278/// compatible for assignment from RHS to LHS. This handles validation of any
4279/// protocol qualifiers on the LHS or RHS.
4280///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004281bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4282 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004283 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4284 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4285
Steve Naroff1329fa02009-07-15 18:40:39 +00004286 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004287 if (LHS->isObjCUnqualifiedIdOrClass() ||
4288 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004289 return true;
4290
John McCall8b07ec22010-05-15 11:32:37 +00004291 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004292 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4293 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004294 false);
4295
John McCall8b07ec22010-05-15 11:32:37 +00004296 // If we have 2 user-defined types, fall into that path.
4297 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004298 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004299
Steve Naroff8e6aee52009-07-23 01:01:38 +00004300 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004301}
4302
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004303/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4304/// for providing type-safty for objective-c pointers used to pass/return
4305/// arguments in block literals. When passed as arguments, passing 'A*' where
4306/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4307/// not OK. For the return type, the opposite is not OK.
4308bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4309 const ObjCObjectPointerType *LHSOPT,
4310 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004311 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004312 return true;
4313
4314 if (LHSOPT->isObjCBuiltinType()) {
4315 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4316 }
4317
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004318 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004319 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4320 QualType(RHSOPT,0),
4321 false);
4322
4323 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4324 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4325 if (LHS && RHS) { // We have 2 user-defined types.
4326 if (LHS != RHS) {
4327 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4328 return false;
4329 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4330 return true;
4331 }
4332 else
4333 return true;
4334 }
4335 return false;
4336}
4337
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004338/// getIntersectionOfProtocols - This routine finds the intersection of set
4339/// of protocols inherited from two distinct objective-c pointer objects.
4340/// It is used to build composite qualifier list of the composite type of
4341/// the conditional expression involving two objective-c pointer objects.
4342static
4343void getIntersectionOfProtocols(ASTContext &Context,
4344 const ObjCObjectPointerType *LHSOPT,
4345 const ObjCObjectPointerType *RHSOPT,
4346 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4347
John McCall8b07ec22010-05-15 11:32:37 +00004348 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4349 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4350 assert(LHS->getInterface() && "LHS must have an interface base");
4351 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004352
4353 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4354 unsigned LHSNumProtocols = LHS->getNumProtocols();
4355 if (LHSNumProtocols > 0)
4356 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4357 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004358 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004359 Context.CollectInheritedProtocols(LHS->getInterface(),
4360 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004361 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4362 LHSInheritedProtocols.end());
4363 }
4364
4365 unsigned RHSNumProtocols = RHS->getNumProtocols();
4366 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004367 ObjCProtocolDecl **RHSProtocols =
4368 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004369 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4370 if (InheritedProtocolSet.count(RHSProtocols[i]))
4371 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4372 }
4373 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004374 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004375 Context.CollectInheritedProtocols(RHS->getInterface(),
4376 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004377 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4378 RHSInheritedProtocols.begin(),
4379 E = RHSInheritedProtocols.end(); I != E; ++I)
4380 if (InheritedProtocolSet.count((*I)))
4381 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004382 }
4383}
4384
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004385/// areCommonBaseCompatible - Returns common base class of the two classes if
4386/// one found. Note that this is O'2 algorithm. But it will be called as the
4387/// last type comparison in a ?-exp of ObjC pointer types before a
4388/// warning is issued. So, its invokation is extremely rare.
4389QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004390 const ObjCObjectPointerType *Lptr,
4391 const ObjCObjectPointerType *Rptr) {
4392 const ObjCObjectType *LHS = Lptr->getObjectType();
4393 const ObjCObjectType *RHS = Rptr->getObjectType();
4394 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4395 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4396 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004397 return QualType();
4398
John McCall8b07ec22010-05-15 11:32:37 +00004399 while ((LDecl = LDecl->getSuperClass())) {
4400 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004401 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004402 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4403 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4404
4405 QualType Result = QualType(LHS, 0);
4406 if (!Protocols.empty())
4407 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4408 Result = getObjCObjectPointerType(Result);
4409 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004410 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004411 }
4412
4413 return QualType();
4414}
4415
John McCall8b07ec22010-05-15 11:32:37 +00004416bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4417 const ObjCObjectType *RHS) {
4418 assert(LHS->getInterface() && "LHS is not an interface type");
4419 assert(RHS->getInterface() && "RHS is not an interface type");
4420
Chris Lattner49af6a42008-04-07 06:51:04 +00004421 // Verify that the base decls are compatible: the RHS must be a subclass of
4422 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004423 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004424 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004425
Chris Lattner49af6a42008-04-07 06:51:04 +00004426 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4427 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004428 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004429 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004430
Chris Lattner49af6a42008-04-07 06:51:04 +00004431 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4432 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004433 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004434 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004435
John McCall8b07ec22010-05-15 11:32:37 +00004436 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4437 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004438 LHSPI != LHSPE; LHSPI++) {
4439 bool RHSImplementsProtocol = false;
4440
4441 // If the RHS doesn't implement the protocol on the left, the types
4442 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004443 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4444 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004445 RHSPI != RHSPE; RHSPI++) {
4446 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004447 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004448 break;
4449 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004450 }
4451 // FIXME: For better diagnostics, consider passing back the protocol name.
4452 if (!RHSImplementsProtocol)
4453 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004454 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004455 // The RHS implements all protocols listed on the LHS.
4456 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004457}
4458
Steve Naroffb7605152009-02-12 17:52:19 +00004459bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4460 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004461 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4462 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004463
Steve Naroff7cae42b2009-07-10 23:34:53 +00004464 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004465 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004466
4467 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4468 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004469}
4470
Mike Stump11289f42009-09-09 15:08:12 +00004471/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00004472/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00004473/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00004474/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman47f77112008-08-22 00:56:42 +00004475bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00004476 if (getLangOptions().CPlusPlus)
4477 return hasSameType(LHS, RHS);
4478
Eli Friedman47f77112008-08-22 00:56:42 +00004479 return !mergeTypes(LHS, RHS).isNull();
4480}
4481
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004482bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4483 return !mergeTypes(LHS, RHS, true).isNull();
4484}
4485
4486QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4487 bool OfBlockPointer) {
John McCall9dd450b2009-09-21 23:43:11 +00004488 const FunctionType *lbase = lhs->getAs<FunctionType>();
4489 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004490 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4491 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00004492 bool allLTypes = true;
4493 bool allRTypes = true;
4494
4495 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004496 QualType retType;
4497 if (OfBlockPointer)
4498 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4499 else
4500 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman47f77112008-08-22 00:56:42 +00004501 if (retType.isNull()) return QualType();
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004502 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004503 allLTypes = false;
Fariborz Jahanian113b8ad2010-02-10 00:32:12 +00004504 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner465fa322008-10-05 17:34:18 +00004505 allRTypes = false;
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004506 // FIXME: double check this
4507 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4508 // rbase->getRegParmAttr() != 0 &&
4509 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004510 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4511 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00004512 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4513 lbaseInfo.getRegParm();
4514 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4515 if (NoReturn != lbaseInfo.getNoReturn() ||
4516 RegParm != lbaseInfo.getRegParm())
4517 allLTypes = false;
4518 if (NoReturn != rbaseInfo.getNoReturn() ||
4519 RegParm != rbaseInfo.getRegParm())
4520 allRTypes = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004521 CallingConv lcc = lbaseInfo.getCC();
4522 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregor8c940862010-01-18 17:14:39 +00004523 // Compatible functions must have compatible calling conventions
John McCallab26cfa2010-02-05 21:31:56 +00004524 if (!isSameCallConv(lcc, rcc))
Douglas Gregor8c940862010-01-18 17:14:39 +00004525 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004526
Eli Friedman47f77112008-08-22 00:56:42 +00004527 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004528 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4529 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004530 unsigned lproto_nargs = lproto->getNumArgs();
4531 unsigned rproto_nargs = rproto->getNumArgs();
4532
4533 // Compatible functions must have the same number of arguments
4534 if (lproto_nargs != rproto_nargs)
4535 return QualType();
4536
4537 // Variadic and non-variadic functions aren't compatible
4538 if (lproto->isVariadic() != rproto->isVariadic())
4539 return QualType();
4540
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00004541 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4542 return QualType();
4543
Eli Friedman47f77112008-08-22 00:56:42 +00004544 // Check argument compatibility
4545 llvm::SmallVector<QualType, 10> types;
4546 for (unsigned i = 0; i < lproto_nargs; i++) {
4547 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4548 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004549 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman47f77112008-08-22 00:56:42 +00004550 if (argtype.isNull()) return QualType();
4551 types.push_back(argtype);
Chris Lattner465fa322008-10-05 17:34:18 +00004552 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4553 allLTypes = false;
4554 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4555 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00004556 }
4557 if (allLTypes) return lhs;
4558 if (allRTypes) return rhs;
4559 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump8c5d7992009-07-25 21:26:53 +00004560 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004561 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004562 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004563 }
4564
4565 if (lproto) allRTypes = false;
4566 if (rproto) allLTypes = false;
4567
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004568 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00004569 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004570 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00004571 if (proto->isVariadic()) return QualType();
4572 // Check that the types are compatible with the types that
4573 // would result from default argument promotions (C99 6.7.5.3p15).
4574 // The only types actually affected are promotable integer
4575 // types and floats, which would be passed as a different
4576 // type depending on whether the prototype is visible.
4577 unsigned proto_nargs = proto->getNumArgs();
4578 for (unsigned i = 0; i < proto_nargs; ++i) {
4579 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00004580
4581 // Look at the promotion type of enum types, since that is the type used
4582 // to pass enum values.
4583 if (const EnumType *Enum = argTy->getAs<EnumType>())
4584 argTy = Enum->getDecl()->getPromotionType();
4585
Eli Friedman47f77112008-08-22 00:56:42 +00004586 if (argTy->isPromotableIntegerType() ||
4587 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4588 return QualType();
4589 }
4590
4591 if (allLTypes) return lhs;
4592 if (allRTypes) return rhs;
4593 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump21e0f892009-07-27 00:44:23 +00004594 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004595 proto->getTypeQuals(),
4596 false, false, 0, 0,
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004597 FunctionType::ExtInfo(NoReturn, RegParm, lcc));
Eli Friedman47f77112008-08-22 00:56:42 +00004598 }
4599
4600 if (allLTypes) return lhs;
4601 if (allRTypes) return rhs;
Rafael Espindola49b85ab2010-03-30 22:15:11 +00004602 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00004603 return getFunctionNoProtoType(retType, Info);
Eli Friedman47f77112008-08-22 00:56:42 +00004604}
4605
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004606QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4607 bool OfBlockPointer) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00004608 // C++ [expr]: If an expression initially has the type "reference to T", the
4609 // type is adjusted to "T" prior to any further analysis, the expression
4610 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004611 // expression is an lvalue unless the reference is an rvalue reference and
4612 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00004613 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4614 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4615
Eli Friedman47f77112008-08-22 00:56:42 +00004616 QualType LHSCan = getCanonicalType(LHS),
4617 RHSCan = getCanonicalType(RHS);
4618
4619 // If two types are identical, they are compatible.
4620 if (LHSCan == RHSCan)
4621 return LHS;
4622
John McCall8ccfcb52009-09-24 19:53:00 +00004623 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004624 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4625 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00004626 if (LQuals != RQuals) {
4627 // If any of these qualifiers are different, we have a type
4628 // mismatch.
4629 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4630 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4631 return QualType();
4632
4633 // Exactly one GC qualifier difference is allowed: __strong is
4634 // okay if the other type has no GC qualifier but is an Objective
4635 // C object pointer (i.e. implicitly strong by default). We fix
4636 // this by pretending that the unqualified type was actually
4637 // qualified __strong.
4638 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4639 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4640 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4641
4642 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4643 return QualType();
4644
4645 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4646 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4647 }
4648 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4649 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4650 }
Eli Friedman47f77112008-08-22 00:56:42 +00004651 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00004652 }
4653
4654 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00004655
Eli Friedmandcca6332009-06-01 01:22:52 +00004656 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4657 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00004658
Chris Lattnerfd652912008-01-14 05:45:46 +00004659 // We want to consider the two function types to be the same for these
4660 // comparisons, just force one to the other.
4661 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4662 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00004663
4664 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00004665 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4666 LHSClass = Type::ConstantArray;
4667 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4668 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00004669
John McCall8b07ec22010-05-15 11:32:37 +00004670 // ObjCInterfaces are just specialized ObjCObjects.
4671 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4672 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4673
Nate Begemance4d7fc2008-04-18 23:10:10 +00004674 // Canonicalize ExtVector -> Vector.
4675 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4676 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00004677
Chris Lattner95554662008-04-07 05:43:21 +00004678 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004679 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00004680 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00004681 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00004682 // Compatibility is based on the underlying type, not the promotion
4683 // type.
John McCall9dd450b2009-09-21 23:43:11 +00004684 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004685 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4686 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004687 }
John McCall9dd450b2009-09-21 23:43:11 +00004688 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00004689 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4690 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00004691 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004692
Eli Friedman47f77112008-08-22 00:56:42 +00004693 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004694 }
Eli Friedman47f77112008-08-22 00:56:42 +00004695
Steve Naroffc6edcbd2008-01-09 22:43:08 +00004696 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00004697 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004698#define TYPE(Class, Base)
4699#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00004700#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004701#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4702#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4703#include "clang/AST/TypeNodes.def"
4704 assert(false && "Non-canonical and dependent types shouldn't get here");
4705 return QualType();
4706
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004707 case Type::LValueReference:
4708 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004709 case Type::MemberPointer:
4710 assert(false && "C++ should never be in mergeTypes");
4711 return QualType();
4712
John McCall8b07ec22010-05-15 11:32:37 +00004713 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004714 case Type::IncompleteArray:
4715 case Type::VariableArray:
4716 case Type::FunctionProto:
4717 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004718 assert(false && "Types are eliminated above");
4719 return QualType();
4720
Chris Lattnerfd652912008-01-14 05:45:46 +00004721 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00004722 {
4723 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004724 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4725 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman47f77112008-08-22 00:56:42 +00004726 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4727 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00004728 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004729 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00004730 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00004731 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004732 return getPointerType(ResultType);
4733 }
Steve Naroff68e167d2008-12-10 17:49:55 +00004734 case Type::BlockPointer:
4735 {
4736 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004737 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4738 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004739 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroff68e167d2008-12-10 17:49:55 +00004740 if (ResultType.isNull()) return QualType();
4741 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4742 return LHS;
4743 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4744 return RHS;
4745 return getBlockPointerType(ResultType);
4746 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004747 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00004748 {
4749 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4750 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4751 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4752 return QualType();
4753
4754 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4755 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4756 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4757 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00004758 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4759 return LHS;
4760 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4761 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00004762 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4763 ArrayType::ArraySizeModifier(), 0);
4764 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4765 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004766 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4767 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00004768 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4769 return LHS;
4770 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4771 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00004772 if (LVAT) {
4773 // FIXME: This isn't correct! But tricky to implement because
4774 // the array's size has to be the size of LHS, but the type
4775 // has to be different.
4776 return LHS;
4777 }
4778 if (RVAT) {
4779 // FIXME: This isn't correct! But tricky to implement because
4780 // the array's size has to be the size of RHS, but the type
4781 // has to be different.
4782 return RHS;
4783 }
Eli Friedman3e62c212008-08-22 01:48:21 +00004784 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4785 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00004786 return getIncompleteArrayType(ResultType,
4787 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00004788 }
Chris Lattnerfd652912008-01-14 05:45:46 +00004789 case Type::FunctionNoProto:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004790 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004791 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004792 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00004793 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00004794 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004795 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00004796 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00004797 case Type::Complex:
4798 // Distinct complex types are incompatible.
4799 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00004800 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00004801 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00004802 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4803 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00004804 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00004805 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00004806 case Type::ObjCObject: {
4807 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00004808 // FIXME: This should be type compatibility, e.g. whether
4809 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00004810 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4811 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4812 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00004813 return LHS;
4814
Eli Friedman47f77112008-08-22 00:56:42 +00004815 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00004816 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004817 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004818 if (OfBlockPointer) {
4819 if (canAssignObjCInterfacesInBlockPointer(
4820 LHS->getAs<ObjCObjectPointerType>(),
4821 RHS->getAs<ObjCObjectPointerType>()))
4822 return LHS;
4823 return QualType();
4824 }
John McCall9dd450b2009-09-21 23:43:11 +00004825 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4826 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004827 return LHS;
4828
Steve Naroffc68cfcf2008-12-10 22:14:21 +00004829 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004830 }
Steve Naroff32e44c02007-10-15 20:41:53 +00004831 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004832
4833 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00004834}
Ted Kremenekfc581a92007-10-31 17:10:13 +00004835
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00004836/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4837/// 'RHS' attributes and returns the merged version; including for function
4838/// return types.
4839QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4840 QualType LHSCan = getCanonicalType(LHS),
4841 RHSCan = getCanonicalType(RHS);
4842 // If two types are identical, they are compatible.
4843 if (LHSCan == RHSCan)
4844 return LHS;
4845 if (RHSCan->isFunctionType()) {
4846 if (!LHSCan->isFunctionType())
4847 return QualType();
4848 QualType OldReturnType =
4849 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4850 QualType NewReturnType =
4851 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4852 QualType ResReturnType =
4853 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4854 if (ResReturnType.isNull())
4855 return QualType();
4856 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4857 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4858 // In either case, use OldReturnType to build the new function type.
4859 const FunctionType *F = LHS->getAs<FunctionType>();
4860 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4861 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4862 QualType ResultType
4863 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4864 FPT->getNumArgs(), FPT->isVariadic(),
4865 FPT->getTypeQuals(),
4866 FPT->hasExceptionSpec(),
4867 FPT->hasAnyExceptionSpec(),
4868 FPT->getNumExceptions(),
4869 FPT->exception_begin(),
4870 Info);
4871 return ResultType;
4872 }
4873 }
4874 return QualType();
4875 }
4876
4877 // If the qualifiers are different, the types can still be merged.
4878 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4879 Qualifiers RQuals = RHSCan.getLocalQualifiers();
4880 if (LQuals != RQuals) {
4881 // If any of these qualifiers are different, we have a type mismatch.
4882 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4883 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4884 return QualType();
4885
4886 // Exactly one GC qualifier difference is allowed: __strong is
4887 // okay if the other type has no GC qualifier but is an Objective
4888 // C object pointer (i.e. implicitly strong by default). We fix
4889 // this by pretending that the unqualified type was actually
4890 // qualified __strong.
4891 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4892 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4893 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4894
4895 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4896 return QualType();
4897
4898 if (GC_L == Qualifiers::Strong)
4899 return LHS;
4900 if (GC_R == Qualifiers::Strong)
4901 return RHS;
4902 return QualType();
4903 }
4904
4905 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4906 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4907 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4908 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4909 if (ResQT == LHSBaseQT)
4910 return LHS;
4911 if (ResQT == RHSBaseQT)
4912 return RHS;
4913 }
4914 return QualType();
4915}
4916
Chris Lattner4ba0cef2008-04-07 07:01:58 +00004917//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004918// Integer Predicates
4919//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00004920
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004921unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl87869bc2009-11-05 21:10:57 +00004922 if (T->isBooleanType())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004923 return 1;
John McCall56774992009-12-09 09:09:27 +00004924 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00004925 T = ET->getDecl()->getIntegerType();
Eli Friedman1efaaea2009-02-13 02:31:07 +00004926 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004927 return (unsigned)getTypeSize(T);
4928}
4929
4930QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4931 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00004932
4933 // Turn <4 x signed int> -> <4 x unsigned int>
4934 if (const VectorType *VTy = T->getAs<VectorType>())
4935 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson22334602010-02-05 00:12:22 +00004936 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattnerec3a1562009-10-17 20:33:28 +00004937
4938 // For enums, we return the unsigned version of the base type.
4939 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004940 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00004941
4942 const BuiltinType *BTy = T->getAs<BuiltinType>();
4943 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004944 switch (BTy->getKind()) {
4945 case BuiltinType::Char_S:
4946 case BuiltinType::SChar:
4947 return UnsignedCharTy;
4948 case BuiltinType::Short:
4949 return UnsignedShortTy;
4950 case BuiltinType::Int:
4951 return UnsignedIntTy;
4952 case BuiltinType::Long:
4953 return UnsignedLongTy;
4954 case BuiltinType::LongLong:
4955 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00004956 case BuiltinType::Int128:
4957 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00004958 default:
4959 assert(0 && "Unexpected signed integer type");
4960 return QualType();
4961 }
4962}
4963
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004964ExternalASTSource::~ExternalASTSource() { }
4965
4966void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00004967
4968
4969//===----------------------------------------------------------------------===//
4970// Builtin Type Computation
4971//===----------------------------------------------------------------------===//
4972
4973/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4974/// pointer over the consumed characters. This returns the resultant type.
Mike Stump11289f42009-09-09 15:08:12 +00004975static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00004976 ASTContext::GetBuiltinTypeError &Error,
4977 bool AllowTypeModifiers = true) {
4978 // Modifiers.
4979 int HowLong = 0;
4980 bool Signed = false, Unsigned = false;
Mike Stump11289f42009-09-09 15:08:12 +00004981
Chris Lattnerecd79c62009-06-14 00:45:47 +00004982 // Read the modifiers first.
4983 bool Done = false;
4984 while (!Done) {
4985 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00004986 default: Done = true; --Str; break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00004987 case 'S':
4988 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4989 assert(!Signed && "Can't use 'S' modifier multiple times!");
4990 Signed = true;
4991 break;
4992 case 'U':
4993 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4994 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4995 Unsigned = true;
4996 break;
4997 case 'L':
4998 assert(HowLong <= 2 && "Can't have LLLL modifier");
4999 ++HowLong;
5000 break;
5001 }
5002 }
5003
5004 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005005
Chris Lattnerecd79c62009-06-14 00:45:47 +00005006 // Read the base type.
5007 switch (*Str++) {
5008 default: assert(0 && "Unknown builtin type letter!");
5009 case 'v':
5010 assert(HowLong == 0 && !Signed && !Unsigned &&
5011 "Bad modifiers used with 'v'!");
5012 Type = Context.VoidTy;
5013 break;
5014 case 'f':
5015 assert(HowLong == 0 && !Signed && !Unsigned &&
5016 "Bad modifiers used with 'f'!");
5017 Type = Context.FloatTy;
5018 break;
5019 case 'd':
5020 assert(HowLong < 2 && !Signed && !Unsigned &&
5021 "Bad modifiers used with 'd'!");
5022 if (HowLong)
5023 Type = Context.LongDoubleTy;
5024 else
5025 Type = Context.DoubleTy;
5026 break;
5027 case 's':
5028 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5029 if (Unsigned)
5030 Type = Context.UnsignedShortTy;
5031 else
5032 Type = Context.ShortTy;
5033 break;
5034 case 'i':
5035 if (HowLong == 3)
5036 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5037 else if (HowLong == 2)
5038 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5039 else if (HowLong == 1)
5040 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5041 else
5042 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5043 break;
5044 case 'c':
5045 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5046 if (Signed)
5047 Type = Context.SignedCharTy;
5048 else if (Unsigned)
5049 Type = Context.UnsignedCharTy;
5050 else
5051 Type = Context.CharTy;
5052 break;
5053 case 'b': // boolean
5054 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5055 Type = Context.BoolTy;
5056 break;
5057 case 'z': // size_t.
5058 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5059 Type = Context.getSizeType();
5060 break;
5061 case 'F':
5062 Type = Context.getCFConstantStringType();
5063 break;
5064 case 'a':
5065 Type = Context.getBuiltinVaListType();
5066 assert(!Type.isNull() && "builtin va list type not initialized!");
5067 break;
5068 case 'A':
5069 // This is a "reference" to a va_list; however, what exactly
5070 // this means depends on how va_list is defined. There are two
5071 // different kinds of va_list: ones passed by value, and ones
5072 // passed by reference. An example of a by-value va_list is
5073 // x86, where va_list is a char*. An example of by-ref va_list
5074 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5075 // we want this argument to be a char*&; for x86-64, we want
5076 // it to be a __va_list_tag*.
5077 Type = Context.getBuiltinVaListType();
5078 assert(!Type.isNull() && "builtin va list type not initialized!");
5079 if (Type->isArrayType()) {
5080 Type = Context.getArrayDecayedType(Type);
5081 } else {
5082 Type = Context.getLValueReferenceType(Type);
5083 }
5084 break;
5085 case 'V': {
5086 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005087 unsigned NumElements = strtoul(Str, &End, 10);
5088 assert(End != Str && "Missing vector size");
Mike Stump11289f42009-09-09 15:08:12 +00005089
Chris Lattnerecd79c62009-06-14 00:45:47 +00005090 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005091
Chris Lattnerecd79c62009-06-14 00:45:47 +00005092 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson22334602010-02-05 00:12:22 +00005093 // FIXME: Don't know what to do about AltiVec.
5094 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005095 break;
5096 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005097 case 'X': {
5098 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5099 Type = Context.getComplexType(ElementType);
5100 break;
5101 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005102 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005103 Type = Context.getFILEType();
5104 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005105 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005106 return QualType();
5107 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005108 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005109 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005110 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005111 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005112 else
5113 Type = Context.getjmp_bufType();
5114
Mike Stump2adb4da2009-07-28 23:47:15 +00005115 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005116 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005117 return QualType();
5118 }
5119 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005120 }
Mike Stump11289f42009-09-09 15:08:12 +00005121
Chris Lattnerecd79c62009-06-14 00:45:47 +00005122 if (!AllowTypeModifiers)
5123 return Type;
Mike Stump11289f42009-09-09 15:08:12 +00005124
Chris Lattnerecd79c62009-06-14 00:45:47 +00005125 Done = false;
5126 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005127 switch (char c = *Str++) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005128 default: Done = true; --Str; break;
5129 case '*':
Chris Lattnerecd79c62009-06-14 00:45:47 +00005130 case '&':
John McCallb8b94662010-03-12 04:21:28 +00005131 {
5132 // Both pointers and references can have their pointee types
5133 // qualified with an address space.
5134 char *End;
5135 unsigned AddrSpace = strtoul(Str, &End, 10);
5136 if (End != Str && AddrSpace != 0) {
5137 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5138 Str = End;
5139 }
5140 }
5141 if (c == '*')
5142 Type = Context.getPointerType(Type);
5143 else
5144 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005145 break;
5146 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5147 case 'C':
John McCall8ccfcb52009-09-24 19:53:00 +00005148 Type = Type.withConst();
Chris Lattnerecd79c62009-06-14 00:45:47 +00005149 break;
Fariborz Jahaniand59baba2010-01-26 22:48:42 +00005150 case 'D':
5151 Type = Context.getVolatileType(Type);
5152 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005153 }
5154 }
Mike Stump11289f42009-09-09 15:08:12 +00005155
Chris Lattnerecd79c62009-06-14 00:45:47 +00005156 return Type;
5157}
5158
5159/// GetBuiltinType - Return the type for the specified builtin.
5160QualType ASTContext::GetBuiltinType(unsigned id,
5161 GetBuiltinTypeError &Error) {
5162 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump11289f42009-09-09 15:08:12 +00005163
Chris Lattnerecd79c62009-06-14 00:45:47 +00005164 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005165
Chris Lattnerecd79c62009-06-14 00:45:47 +00005166 Error = GE_None;
5167 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5168 if (Error != GE_None)
5169 return QualType();
5170 while (TypeStr[0] && TypeStr[0] != '.') {
5171 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5172 if (Error != GE_None)
5173 return QualType();
5174
5175 // Do array -> pointer decay. The builtin should use the decayed type.
5176 if (Ty->isArrayType())
5177 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005178
Chris Lattnerecd79c62009-06-14 00:45:47 +00005179 ArgTypes.push_back(Ty);
5180 }
5181
5182 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5183 "'.' should only occur at end of builtin type list!");
5184
5185 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5186 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5187 return getFunctionNoProtoType(ResType);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005188
5189 // FIXME: Should we create noreturn types?
Chris Lattnerecd79c62009-06-14 00:45:47 +00005190 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00005191 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005192 FunctionType::ExtInfo());
Chris Lattnerecd79c62009-06-14 00:45:47 +00005193}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005194
5195QualType
5196ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5197 // Perform the usual unary conversions. We do this early so that
5198 // integral promotions to "int" can allow us to exit early, in the
5199 // lhs == rhs check. Also, for conversion purposes, we ignore any
5200 // qualifiers. For example, "const float" and "float" are
5201 // equivalent.
5202 if (lhs->isPromotableIntegerType())
5203 lhs = getPromotedIntegerType(lhs);
5204 else
5205 lhs = lhs.getUnqualifiedType();
5206 if (rhs->isPromotableIntegerType())
5207 rhs = getPromotedIntegerType(rhs);
5208 else
5209 rhs = rhs.getUnqualifiedType();
5210
5211 // If both types are identical, no conversion is needed.
5212 if (lhs == rhs)
5213 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005214
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005215 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5216 // The caller can deal with this (e.g. pointer + int).
5217 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5218 return lhs;
Mike Stump11289f42009-09-09 15:08:12 +00005219
5220 // At this point, we have two different arithmetic types.
5221
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005222 // Handle complex types first (C99 6.3.1.8p1).
5223 if (lhs->isComplexType() || rhs->isComplexType()) {
5224 // if we have an integer operand, the result is the complex type.
Mike Stump11289f42009-09-09 15:08:12 +00005225 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005226 // convert the rhs to the lhs complex type.
5227 return lhs;
5228 }
Mike Stump11289f42009-09-09 15:08:12 +00005229 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005230 // convert the lhs to the rhs complex type.
5231 return rhs;
5232 }
5233 // This handles complex/complex, complex/float, or float/complex.
Mike Stump11289f42009-09-09 15:08:12 +00005234 // When both operands are complex, the shorter operand is converted to the
5235 // type of the longer, and that is the type of the result. This corresponds
5236 // to what is done when combining two real floating-point operands.
5237 // The fun begins when size promotion occur across type domains.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005238 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump11289f42009-09-09 15:08:12 +00005239 // floating-point type, the less precise type is converted, within it's
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005240 // real or complex domain, to the precision of the other type. For example,
Mike Stump11289f42009-09-09 15:08:12 +00005241 // when combining a "long double" with a "double _Complex", the
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005242 // "double _Complex" is promoted to "long double _Complex".
5243 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005244
5245 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005246 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump11289f42009-09-09 15:08:12 +00005247 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005248 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump11289f42009-09-09 15:08:12 +00005249 }
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005250 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5251 // domains match. This is a requirement for our implementation, C99
5252 // does not require this promotion.
5253 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5254 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5255 return rhs;
5256 } else { // handle "_Complex double, double".
5257 return lhs;
5258 }
5259 }
5260 return lhs; // The domain/size match exactly.
5261 }
5262 // Now handle "real" floating types (i.e. float, double, long double).
5263 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5264 // if we have an integer operand, the result is the real floating type.
5265 if (rhs->isIntegerType()) {
5266 // convert rhs to the lhs floating point type.
5267 return lhs;
5268 }
5269 if (rhs->isComplexIntegerType()) {
5270 // convert rhs to the complex floating point type.
5271 return getComplexType(lhs);
5272 }
5273 if (lhs->isIntegerType()) {
5274 // convert lhs to the rhs floating point type.
5275 return rhs;
5276 }
Mike Stump11289f42009-09-09 15:08:12 +00005277 if (lhs->isComplexIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005278 // convert lhs to the complex floating point type.
5279 return getComplexType(rhs);
5280 }
5281 // We have two real floating types, float/complex combos were handled above.
5282 // Convert the smaller operand to the bigger result.
5283 int result = getFloatingTypeOrder(lhs, rhs);
5284 if (result > 0) // convert the rhs
5285 return lhs;
5286 assert(result < 0 && "illegal float comparison");
5287 return rhs; // convert the lhs
5288 }
5289 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5290 // Handle GCC complex int extension.
5291 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5292 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5293
5294 if (lhsComplexInt && rhsComplexInt) {
Mike Stump11289f42009-09-09 15:08:12 +00005295 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005296 rhsComplexInt->getElementType()) >= 0)
5297 return lhs; // convert the rhs
5298 return rhs;
5299 } else if (lhsComplexInt && rhs->isIntegerType()) {
5300 // convert the rhs to the lhs complex type.
5301 return lhs;
5302 } else if (rhsComplexInt && lhs->isIntegerType()) {
5303 // convert the lhs to the rhs complex type.
5304 return rhs;
5305 }
5306 }
5307 // Finally, we have two differing integer types.
5308 // The rules for this case are in C99 6.3.1.8
5309 int compare = getIntegerTypeOrder(lhs, rhs);
5310 bool lhsSigned = lhs->isSignedIntegerType(),
5311 rhsSigned = rhs->isSignedIntegerType();
5312 QualType destType;
5313 if (lhsSigned == rhsSigned) {
5314 // Same signedness; use the higher-ranked type
5315 destType = compare >= 0 ? lhs : rhs;
5316 } else if (compare != (lhsSigned ? 1 : -1)) {
5317 // The unsigned type has greater than or equal rank to the
5318 // signed type, so use the unsigned type
5319 destType = lhsSigned ? rhs : lhs;
5320 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5321 // The two types are different widths; if we are here, that
5322 // means the signed type is larger than the unsigned type, so
5323 // use the signed type.
5324 destType = lhsSigned ? lhs : rhs;
5325 } else {
5326 // The signed type is higher-ranked than the unsigned type,
5327 // but isn't actually any bigger (like unsigned int and long
5328 // on most 32-bit systems). Use the unsigned type corresponding
5329 // to the signed type.
5330 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5331 }
5332 return destType;
5333}