blob: 63e84d41313828bd6d487234d2b5acba5339b085 [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"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis53c59df2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000034
Chris Lattnerddc135e2006-11-10 06:34:16 +000035using namespace clang;
36
Douglas Gregor9672f922010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Steve Naroff0af91202007-04-27 21:51:21 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor7dbfb462010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000072 if (NTTP->isExpandedParameterPack()) {
73 ID.AddBoolean(true);
74 ID.AddInteger(NTTP->getNumExpansionTypes());
75 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
76 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
77 } else
78 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000079 continue;
80 }
81
82 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
83 ID.AddInteger(2);
84 Profile(ID, TTP);
85 }
86}
87
88TemplateTemplateParmDecl *
89ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000090 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000091 // Check if we already have a canonical template template parameter.
92 llvm::FoldingSetNodeID ID;
93 CanonicalTemplateTemplateParm::Profile(ID, TTP);
94 void *InsertPos = 0;
95 CanonicalTemplateTemplateParm *Canonical
96 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
97 if (Canonical)
98 return Canonical->getParam();
99
100 // Build a canonical template parameter list.
101 TemplateParameterList *Params = TTP->getTemplateParameters();
102 llvm::SmallVector<NamedDecl *, 4> CanonParams;
103 CanonParams.reserve(Params->size());
104 for (TemplateParameterList::const_iterator P = Params->begin(),
105 PEnd = Params->end();
106 P != PEnd; ++P) {
107 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
108 CanonParams.push_back(
109 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
110 SourceLocation(), TTP->getDepth(),
111 TTP->getIndex(), 0, false,
112 TTP->isParameterPack()));
113 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000114 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
115 QualType T = getCanonicalType(NTTP->getType());
116 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
117 NonTypeTemplateParmDecl *Param;
118 if (NTTP->isExpandedParameterPack()) {
119 llvm::SmallVector<QualType, 2> ExpandedTypes;
120 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
121 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
122 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
123 ExpandedTInfos.push_back(
124 getTrivialTypeSourceInfo(ExpandedTypes.back()));
125 }
126
127 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
128 SourceLocation(),
129 NTTP->getDepth(),
130 NTTP->getPosition(), 0,
131 T,
132 TInfo,
133 ExpandedTypes.data(),
134 ExpandedTypes.size(),
135 ExpandedTInfos.data());
136 } else {
137 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
138 SourceLocation(),
139 NTTP->getDepth(),
140 NTTP->getPosition(), 0,
141 T,
142 NTTP->isParameterPack(),
143 TInfo);
144 }
145 CanonParams.push_back(Param);
146
147 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000148 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
149 cast<TemplateTemplateParmDecl>(*P)));
150 }
151
152 TemplateTemplateParmDecl *CanonTTP
153 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
154 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000155 TTP->getPosition(),
156 TTP->isParameterPack(),
157 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000158 TemplateParameterList::Create(*this, SourceLocation(),
159 SourceLocation(),
160 CanonParams.data(),
161 CanonParams.size(),
162 SourceLocation()));
163
164 // Get the new insert position for the node we care about.
165 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
166 assert(Canonical == 0 && "Shouldn't be in the map!");
167 (void)Canonical;
168
169 // Create the canonical template template parameter entry.
170 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
171 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
172 return CanonTTP;
173}
174
Charles Davis53c59df2010-08-16 03:33:14 +0000175CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000176 if (!LangOpts.CPlusPlus) return 0;
177
Charles Davis6bcb07a2010-08-19 02:18:14 +0000178 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000179 case CXXABI_ARM:
180 return CreateARMCXXABI(*this);
181 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000182 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000183 case CXXABI_Microsoft:
184 return CreateMicrosoftCXXABI(*this);
185 }
John McCall86353412010-08-21 22:46:04 +0000186 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000187}
188
Chris Lattner465fa322008-10-05 17:34:18 +0000189ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000190 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000191 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000192 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000193 unsigned size_reserve) :
John McCall773cc982010-06-11 11:07:21 +0000194 TemplateSpecializationTypes(this_()),
195 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000196 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
197 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000198 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000199 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000200 NullTypeSourceInfo(QualType()),
Charles Davis53c59df2010-08-16 03:33:14 +0000201 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000202 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000203 BuiltinInfo(builtins),
204 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000205 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000206 LastSDM(0, 0),
207 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000208 ObjCIdRedefinitionType = QualType();
209 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000210 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000211 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000212 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000213 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000214}
215
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000216ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000217 // Release the DenseMaps associated with DeclContext objects.
218 // FIXME: Is this the ideal solution?
219 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000220
Douglas Gregor5b11d492010-07-25 17:53:33 +0000221 // Call all of the deallocation functions.
222 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
223 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000224
Douglas Gregor832940b2010-03-02 23:58:15 +0000225 // Release all of the memory associated with overridden C++ methods.
226 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
227 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
228 OM != OMEnd; ++OM)
229 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000230
Ted Kremenek076baeb2010-06-08 23:00:58 +0000231 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000232 // because they can contain DenseMaps.
233 for (llvm::DenseMap<const ObjCContainerDecl*,
234 const ASTRecordLayout*>::iterator
235 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
236 // Increment in loop to prevent using deallocated memory.
237 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
238 R->Destroy(*this);
239
Ted Kremenek076baeb2010-06-08 23:00:58 +0000240 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
241 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
242 // Increment in loop to prevent using deallocated memory.
243 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
244 R->Destroy(*this);
245 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000246
247 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
248 AEnd = DeclAttrs.end();
249 A != AEnd; ++A)
250 A->second->~AttrVec();
251}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000252
Douglas Gregor1a809332010-05-23 18:26:36 +0000253void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
254 Deallocations.push_back(std::make_pair(Callback, Data));
255}
256
Mike Stump11289f42009-09-09 15:08:12 +0000257void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000258ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
259 ExternalSource.reset(Source.take());
260}
261
Chris Lattner4eb445d2007-01-26 01:27:23 +0000262void ASTContext::PrintStats() const {
263 fprintf(stderr, "*** AST Context Stats:\n");
264 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000265
Douglas Gregora30d0462009-05-26 14:40:08 +0000266 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000267#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000268#define ABSTRACT_TYPE(Name, Parent)
269#include "clang/AST/TypeNodes.def"
270 0 // Extra
271 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000272
Chris Lattner4eb445d2007-01-26 01:27:23 +0000273 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
274 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000275 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000276 }
277
Douglas Gregora30d0462009-05-26 14:40:08 +0000278 unsigned Idx = 0;
279 unsigned TotalBytes = 0;
280#define TYPE(Name, Parent) \
281 if (counts[Idx]) \
282 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
283 TotalBytes += counts[Idx] * sizeof(Name##Type); \
284 ++Idx;
285#define ABSTRACT_TYPE(Name, Parent)
286#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000287
Douglas Gregora30d0462009-05-26 14:40:08 +0000288 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000289
Douglas Gregor7454c562010-07-02 20:37:36 +0000290 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000291 fprintf(stderr, " %u/%u implicit default constructors created\n",
292 NumImplicitDefaultConstructorsDeclared,
293 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000294 fprintf(stderr, " %u/%u implicit copy constructors created\n",
295 NumImplicitCopyConstructorsDeclared,
296 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000297 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
298 NumImplicitCopyAssignmentOperatorsDeclared,
299 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000300 fprintf(stderr, " %u/%u implicit destructors created\n",
301 NumImplicitDestructorsDeclared, NumImplicitDestructors);
302
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000303 if (ExternalSource.get()) {
304 fprintf(stderr, "\n");
305 ExternalSource->PrintStats();
306 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000307
Douglas Gregor5b11d492010-07-25 17:53:33 +0000308 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000309}
310
311
John McCall48f2d582009-10-23 23:03:21 +0000312void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000313 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000314 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000315 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000316}
317
Chris Lattner970e54e2006-11-12 00:37:36 +0000318void ASTContext::InitBuiltinTypes() {
319 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000320
Chris Lattner970e54e2006-11-12 00:37:36 +0000321 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000322 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000323
Chris Lattner970e54e2006-11-12 00:37:36 +0000324 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000325 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000326 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000327 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000328 InitBuiltinType(CharTy, BuiltinType::Char_S);
329 else
330 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000331 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000332 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
333 InitBuiltinType(ShortTy, BuiltinType::Short);
334 InitBuiltinType(IntTy, BuiltinType::Int);
335 InitBuiltinType(LongTy, BuiltinType::Long);
336 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000337
Chris Lattner970e54e2006-11-12 00:37:36 +0000338 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000339 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
340 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
341 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
342 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
343 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000344
Chris Lattner970e54e2006-11-12 00:37:36 +0000345 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000346 InitBuiltinType(FloatTy, BuiltinType::Float);
347 InitBuiltinType(DoubleTy, BuiltinType::Double);
348 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000349
Chris Lattnerf122cef2009-04-30 02:43:43 +0000350 // GNU extension, 128-bit integers.
351 InitBuiltinType(Int128Ty, BuiltinType::Int128);
352 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
353
Chris Lattnerad3467e2010-12-25 23:25:43 +0000354 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
355 if (!LangOpts.ShortWChar)
356 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
357 else // -fshort-wchar makes wchar_t be unsigned.
358 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
359 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000360 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000361
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000362 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
363 InitBuiltinType(Char16Ty, BuiltinType::Char16);
364 else // C99
365 Char16Ty = getFromTargetType(Target.getChar16Type());
366
367 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
368 InitBuiltinType(Char32Ty, BuiltinType::Char32);
369 else // C99
370 Char32Ty = getFromTargetType(Target.getChar32Type());
371
Douglas Gregor4619e432008-12-05 23:32:09 +0000372 // Placeholder type for type-dependent expressions whose type is
373 // completely unknown. No code should ever check a type against
374 // DependentTy and users should never see it; however, it is here to
375 // help diagnose failures to properly check for type-dependent
376 // expressions.
377 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000378
John McCall36e7fe32010-10-12 00:20:44 +0000379 // Placeholder type for functions.
380 InitBuiltinType(OverloadTy, BuiltinType::Overload);
381
Mike Stump11289f42009-09-09 15:08:12 +0000382 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlsson082acde2009-06-26 18:41:36 +0000383 // not yet been deduced.
John McCall36e7fe32010-10-12 00:20:44 +0000384 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump11289f42009-09-09 15:08:12 +0000385
Chris Lattner970e54e2006-11-12 00:37:36 +0000386 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000387 FloatComplexTy = getComplexType(FloatTy);
388 DoubleComplexTy = getComplexType(DoubleTy);
389 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000390
Steve Naroff66e9f332007-10-15 14:41:52 +0000391 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000392
Steve Naroff1329fa02009-07-15 18:40:39 +0000393 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
394 ObjCIdTypedefType = QualType();
395 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000396 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000397
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000398 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000399 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
400 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000401 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000402
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000403 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000404
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000405 // void * type
406 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000407
408 // nullptr type (C++0x 2.14.7)
409 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000410}
411
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000412Diagnostic &ASTContext::getDiagnostics() const {
413 return SourceMgr.getDiagnostics();
414}
415
Douglas Gregor561eceb2010-08-30 16:49:28 +0000416AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
417 AttrVec *&Result = DeclAttrs[D];
418 if (!Result) {
419 void *Mem = Allocate(sizeof(AttrVec));
420 Result = new (Mem) AttrVec;
421 }
422
423 return *Result;
424}
425
426/// \brief Erase the attributes corresponding to the given declaration.
427void ASTContext::eraseDeclAttrs(const Decl *D) {
428 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
429 if (Pos != DeclAttrs.end()) {
430 Pos->second->~AttrVec();
431 DeclAttrs.erase(Pos);
432 }
433}
434
435
Douglas Gregor86d142a2009-10-08 07:24:58 +0000436MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000437ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000438 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000439 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000440 = InstantiatedFromStaticDataMember.find(Var);
441 if (Pos == InstantiatedFromStaticDataMember.end())
442 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000444 return Pos->second;
445}
446
Mike Stump11289f42009-09-09 15:08:12 +0000447void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000448ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000449 TemplateSpecializationKind TSK,
450 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000451 assert(Inst->isStaticDataMember() && "Not a static data member");
452 assert(Tmpl->isStaticDataMember() && "Not a static data member");
453 assert(!InstantiatedFromStaticDataMember[Inst] &&
454 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000455 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000456 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000457}
458
John McCalle61f2ba2009-11-18 02:36:19 +0000459NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000460ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000461 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000462 = InstantiatedFromUsingDecl.find(UUD);
463 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000464 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000465
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000466 return Pos->second;
467}
468
469void
John McCallb96ec562009-12-04 22:46:56 +0000470ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
471 assert((isa<UsingDecl>(Pattern) ||
472 isa<UnresolvedUsingValueDecl>(Pattern) ||
473 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
474 "pattern decl is not a using decl");
475 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
476 InstantiatedFromUsingDecl[Inst] = Pattern;
477}
478
479UsingShadowDecl *
480ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
481 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
482 = InstantiatedFromUsingShadowDecl.find(Inst);
483 if (Pos == InstantiatedFromUsingShadowDecl.end())
484 return 0;
485
486 return Pos->second;
487}
488
489void
490ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
491 UsingShadowDecl *Pattern) {
492 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
493 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000494}
495
Anders Carlsson5da84842009-09-01 04:26:58 +0000496FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
497 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
498 = InstantiatedFromUnnamedFieldDecl.find(Field);
499 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
500 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000501
Anders Carlsson5da84842009-09-01 04:26:58 +0000502 return Pos->second;
503}
504
505void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
506 FieldDecl *Tmpl) {
507 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
508 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
509 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
510 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000511
Anders Carlsson5da84842009-09-01 04:26:58 +0000512 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
513}
514
Douglas Gregor832940b2010-03-02 23:58:15 +0000515ASTContext::overridden_cxx_method_iterator
516ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
517 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
518 = OverriddenMethods.find(Method);
519 if (Pos == OverriddenMethods.end())
520 return 0;
521
522 return Pos->second.begin();
523}
524
525ASTContext::overridden_cxx_method_iterator
526ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
527 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
528 = OverriddenMethods.find(Method);
529 if (Pos == OverriddenMethods.end())
530 return 0;
531
532 return Pos->second.end();
533}
534
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000535unsigned
536ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
537 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
538 = OverriddenMethods.find(Method);
539 if (Pos == OverriddenMethods.end())
540 return 0;
541
542 return Pos->second.size();
543}
544
Douglas Gregor832940b2010-03-02 23:58:15 +0000545void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
546 const CXXMethodDecl *Overridden) {
547 OverriddenMethods[Method].push_back(Overridden);
548}
549
Chris Lattner53cfe802007-07-18 17:52:12 +0000550//===----------------------------------------------------------------------===//
551// Type Sizing and Analysis
552//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000553
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000554/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
555/// scalar floating point type.
556const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000557 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000558 assert(BT && "Not a floating point type!");
559 switch (BT->getKind()) {
560 default: assert(0 && "Not a floating point type!");
561 case BuiltinType::Float: return Target.getFloatFormat();
562 case BuiltinType::Double: return Target.getDoubleFormat();
563 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
564 }
565}
566
Ken Dyck160146e2010-01-27 17:10:57 +0000567/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000568/// specified decl. Note that bitfields do not have a valid alignment, so
569/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000570/// If @p RefAsPointee, references are treated like their underlying type
571/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000572CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000573 unsigned Align = Target.getCharWidth();
574
John McCall94268702010-10-08 18:24:19 +0000575 bool UseAlignAttrOnly = false;
576 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
577 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000578
John McCall94268702010-10-08 18:24:19 +0000579 // __attribute__((aligned)) can increase or decrease alignment
580 // *except* on a struct or struct member, where it only increases
581 // alignment unless 'packed' is also specified.
582 //
583 // It is an error for [[align]] to decrease alignment, so we can
584 // ignore that possibility; Sema should diagnose it.
585 if (isa<FieldDecl>(D)) {
586 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
587 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
588 } else {
589 UseAlignAttrOnly = true;
590 }
591 }
592
John McCall4e819612011-01-20 07:57:12 +0000593 // If we're using the align attribute only, just ignore everything
594 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000595 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000596 // do nothing
597
John McCall94268702010-10-08 18:24:19 +0000598 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000599 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000600 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000601 if (RefAsPointee)
602 T = RT->getPointeeType();
603 else
604 T = getPointerType(RT->getPointeeType());
605 }
606 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000607 // Adjust alignments of declarations with array type by the
608 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000609 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000610 const ArrayType *arrayType;
611 if (MinWidth && (arrayType = getAsArrayType(T))) {
612 if (isa<VariableArrayType>(arrayType))
613 Align = std::max(Align, Target.getLargeArrayAlign());
614 else if (isa<ConstantArrayType>(arrayType) &&
615 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
616 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000617
John McCall33ddac02011-01-19 10:06:00 +0000618 // Walk through any array types while we're at it.
619 T = getBaseElementType(arrayType);
620 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000621 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
622 }
John McCall4e819612011-01-20 07:57:12 +0000623
624 // Fields can be subject to extra alignment constraints, like if
625 // the field is packed, the struct is packed, or the struct has a
626 // a max-field-alignment constraint (#pragma pack). So calculate
627 // the actual alignment of the field within the struct, and then
628 // (as we're expected to) constrain that by the alignment of the type.
629 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
630 // So calculate the alignment of the field.
631 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
632
633 // Start with the record's overall alignment.
634 unsigned fieldAlign = layout.getAlignment();
635
636 // Use the GCD of that and the offset within the record.
637 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
638 if (offset > 0) {
639 // Alignment is always a power of 2, so the GCD will be a power of 2,
640 // which means we get to do this crazy thing instead of Euclid's.
641 uint64_t lowBitOfOffset = offset & (~offset + 1);
642 if (lowBitOfOffset < fieldAlign)
643 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
644 }
645
646 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000647 }
Chris Lattner68061312009-01-24 21:53:27 +0000648 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000649
Ken Dyckcc56c542011-01-15 18:38:59 +0000650 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000651}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000652
John McCall87fe5d52010-05-20 01:18:31 +0000653std::pair<CharUnits, CharUnits>
654ASTContext::getTypeInfoInChars(const Type *T) {
655 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000656 return std::make_pair(toCharUnitsFromBits(Info.first),
657 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000658}
659
660std::pair<CharUnits, CharUnits>
661ASTContext::getTypeInfoInChars(QualType T) {
662 return getTypeInfoInChars(T.getTypePtr());
663}
664
Chris Lattner983a8bb2007-07-13 22:13:22 +0000665/// getTypeSize - Return the size of the specified type, in bits. This method
666/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000667///
668/// FIXME: Pointers into different addr spaces could have different sizes and
669/// alignment requirements: getPointerInfo should take an AddrSpace, this
670/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000671std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000672ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000673 uint64_t Width=0;
674 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000675 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000676#define TYPE(Class, Base)
677#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000678#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000679#define DEPENDENT_TYPE(Class, Base) case Type::Class:
680#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000681 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000682 break;
683
Chris Lattner355332d2007-07-13 22:27:08 +0000684 case Type::FunctionNoProto:
685 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000686 // GCC extension: alignof(function) = 32 bits
687 Width = 0;
688 Align = 32;
689 break;
690
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000691 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000692 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000693 Width = 0;
694 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
695 break;
696
Steve Naroff5c131802007-08-30 01:06:46 +0000697 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000698 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner37e05872008-03-05 18:54:05 +0000700 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000701 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000702 Align = EltInfo.second;
703 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000704 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000705 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000706 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000707 const VectorType *VT = cast<VectorType>(T);
708 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
709 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000710 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000711 // If the alignment is not a power of 2, round up to the next power of 2.
712 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000713 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000714 Align = llvm::NextPowerOf2(Align);
715 Width = llvm::RoundUpToAlignment(Width, Align);
716 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000717 break;
718 }
Chris Lattner647fb222007-07-18 18:26:58 +0000719
Chris Lattner7570e9c2008-03-08 08:52:55 +0000720 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000721 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000722 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000723 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000724 // GCC extension: alignof(void) = 8 bits.
725 Width = 0;
726 Align = 8;
727 break;
728
Chris Lattner6a4f7452007-12-19 19:23:28 +0000729 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000730 Width = Target.getBoolWidth();
731 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000732 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000733 case BuiltinType::Char_S:
734 case BuiltinType::Char_U:
735 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000736 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000737 Width = Target.getCharWidth();
738 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000739 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000740 case BuiltinType::WChar_S:
741 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000742 Width = Target.getWCharWidth();
743 Align = Target.getWCharAlign();
744 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000745 case BuiltinType::Char16:
746 Width = Target.getChar16Width();
747 Align = Target.getChar16Align();
748 break;
749 case BuiltinType::Char32:
750 Width = Target.getChar32Width();
751 Align = Target.getChar32Align();
752 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000753 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000754 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000755 Width = Target.getShortWidth();
756 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000757 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000758 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000759 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000760 Width = Target.getIntWidth();
761 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000762 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000763 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000764 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000765 Width = Target.getLongWidth();
766 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000767 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000768 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000769 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000770 Width = Target.getLongLongWidth();
771 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000772 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000773 case BuiltinType::Int128:
774 case BuiltinType::UInt128:
775 Width = 128;
776 Align = 128; // int128_t is 128-bit aligned on all targets.
777 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000778 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000779 Width = Target.getFloatWidth();
780 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000781 break;
782 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000783 Width = Target.getDoubleWidth();
784 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000785 break;
786 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000787 Width = Target.getLongDoubleWidth();
788 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000789 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000790 case BuiltinType::NullPtr:
791 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
792 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000793 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000794 case BuiltinType::ObjCId:
795 case BuiltinType::ObjCClass:
796 case BuiltinType::ObjCSel:
797 Width = Target.getPointerWidth(0);
798 Align = Target.getPointerAlign(0);
799 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000800 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000801 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000802 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000803 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000804 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000805 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000806 case Type::BlockPointer: {
807 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
808 Width = Target.getPointerWidth(AS);
809 Align = Target.getPointerAlign(AS);
810 break;
811 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000812 case Type::LValueReference:
813 case Type::RValueReference: {
814 // alignof and sizeof should never enter this code path here, so we go
815 // the pointer route.
816 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
817 Width = Target.getPointerWidth(AS);
818 Align = Target.getPointerAlign(AS);
819 break;
820 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000821 case Type::Pointer: {
822 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000823 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000824 Align = Target.getPointerAlign(AS);
825 break;
826 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000827 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000828 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000829 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000830 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000831 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000832 Align = PtrDiffInfo.second;
833 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000834 }
Chris Lattner647fb222007-07-18 18:26:58 +0000835 case Type::Complex: {
836 // Complex types have the same alignment as their elements, but twice the
837 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000838 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000839 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000840 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000841 Align = EltInfo.second;
842 break;
843 }
John McCall8b07ec22010-05-15 11:32:37 +0000844 case Type::ObjCObject:
845 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000846 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000847 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000848 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
849 Width = Layout.getSize();
850 Align = Layout.getAlignment();
851 break;
852 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000853 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000854 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000855 const TagType *TT = cast<TagType>(T);
856
857 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000858 Width = 1;
859 Align = 1;
860 break;
861 }
Mike Stump11289f42009-09-09 15:08:12 +0000862
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000863 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000864 return getTypeInfo(ET->getDecl()->getIntegerType());
865
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000866 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000867 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
868 Width = Layout.getSize();
869 Align = Layout.getAlignment();
Chris Lattner49a953a2007-07-23 22:46:22 +0000870 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000871 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000872
Chris Lattner63d2b362009-10-22 05:17:15 +0000873 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000874 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
875 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000876
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000877 case Type::Paren:
878 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
879
Douglas Gregoref462e62009-04-30 17:32:17 +0000880 case Type::Typedef: {
881 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000882 std::pair<uint64_t, unsigned> Info
883 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
884 Align = std::max(Typedef->getMaxAlignment(), Info.second);
885 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000886 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000887 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000888
889 case Type::TypeOfExpr:
890 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
891 .getTypePtr());
892
893 case Type::TypeOf:
894 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
895
Anders Carlsson81df7b82009-06-24 19:06:50 +0000896 case Type::Decltype:
897 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
898 .getTypePtr());
899
Abramo Bagnara6150c882010-05-11 21:36:43 +0000900 case Type::Elaborated:
901 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000902
John McCall81904512011-01-06 01:58:22 +0000903 case Type::Attributed:
904 return getTypeInfo(
905 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
906
Douglas Gregoref462e62009-04-30 17:32:17 +0000907 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000908 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000909 "Cannot request the size of a dependent type");
910 // FIXME: this is likely to be wrong once we support template
911 // aliases, since a template alias could refer to a typedef that
912 // has an __aligned__ attribute on it.
913 return getTypeInfo(getCanonicalType(T));
914 }
Mike Stump11289f42009-09-09 15:08:12 +0000915
Chris Lattner53cfe802007-07-18 17:52:12 +0000916 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000917 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000918}
919
Ken Dyckcc56c542011-01-15 18:38:59 +0000920/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
921CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
922 return CharUnits::fromQuantity(BitSize / getCharWidth());
923}
924
Ken Dyck8c89d592009-12-22 14:23:30 +0000925/// getTypeSizeInChars - Return the size of the specified type, in characters.
926/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000927CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000928 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000929}
Jay Foad39c79802011-01-12 09:06:06 +0000930CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000931 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000932}
933
Ken Dycka6046ab2010-01-26 17:25:18 +0000934/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000935/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000936CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000937 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000938}
Jay Foad39c79802011-01-12 09:06:06 +0000939CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000940 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000941}
942
Chris Lattnera3402cd2009-01-27 18:08:34 +0000943/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
944/// type for the current target in bits. This can be different than the ABI
945/// alignment in cases where it is beneficial for performance to overalign
946/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000947unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000948 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000949
950 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000951 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000952 T = CT->getElementType().getTypePtr();
953 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
954 T->isSpecificBuiltinType(BuiltinType::LongLong))
955 return std::max(ABIAlign, (unsigned)getTypeSize(T));
956
Chris Lattnera3402cd2009-01-27 18:08:34 +0000957 return ABIAlign;
958}
959
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000960/// ShallowCollectObjCIvars -
961/// Collect all ivars, including those synthesized, in the current class.
962///
963void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +0000964 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000965 // FIXME. This need be removed but there are two many places which
966 // assume const-ness of ObjCInterfaceDecl
967 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
968 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
969 Iv= Iv->getNextIvar())
970 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +0000971}
972
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000973/// DeepCollectObjCIvars -
974/// This routine first collects all declared, but not synthesized, ivars in
975/// super class and then collects all ivars, including those synthesized for
976/// current class. This routine is used for implementation of current class
977/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000978///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000979void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
980 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +0000981 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000982 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
983 DeepCollectObjCIvars(SuperClass, false, Ivars);
984 if (!leafClass) {
985 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
986 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +0000987 Ivars.push_back(*I);
988 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +0000989 else
990 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +0000991}
992
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000993/// CollectInheritedProtocols - Collect all protocols in current class and
994/// those inherited by it.
995void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +0000996 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +0000997 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000998 // We can use protocol_iterator here instead of
999 // all_referenced_protocol_iterator since we are walking all categories.
1000 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1001 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001002 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001003 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001004 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001005 PE = Proto->protocol_end(); P != PE; ++P) {
1006 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001007 CollectInheritedProtocols(*P, Protocols);
1008 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001009 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001010
1011 // Categories of this Interface.
1012 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1013 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1014 CollectInheritedProtocols(CDeclChain, Protocols);
1015 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1016 while (SD) {
1017 CollectInheritedProtocols(SD, Protocols);
1018 SD = SD->getSuperClass();
1019 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001020 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001021 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001022 PE = OC->protocol_end(); P != PE; ++P) {
1023 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001024 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001025 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1026 PE = Proto->protocol_end(); P != PE; ++P)
1027 CollectInheritedProtocols(*P, Protocols);
1028 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001029 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001030 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1031 PE = OP->protocol_end(); P != PE; ++P) {
1032 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001033 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001034 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1035 PE = Proto->protocol_end(); P != PE; ++P)
1036 CollectInheritedProtocols(*P, Protocols);
1037 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001038 }
1039}
1040
Jay Foad39c79802011-01-12 09:06:06 +00001041unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001042 unsigned count = 0;
1043 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001044 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1045 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001046 count += CDecl->ivar_size();
1047
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001048 // Count ivar defined in this class's implementation. This
1049 // includes synthesized ivars.
1050 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001051 count += ImplDecl->ivar_size();
1052
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001053 return count;
1054}
1055
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001056/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1057ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1058 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1059 I = ObjCImpls.find(D);
1060 if (I != ObjCImpls.end())
1061 return cast<ObjCImplementationDecl>(I->second);
1062 return 0;
1063}
1064/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1065ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1066 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1067 I = ObjCImpls.find(D);
1068 if (I != ObjCImpls.end())
1069 return cast<ObjCCategoryImplDecl>(I->second);
1070 return 0;
1071}
1072
1073/// \brief Set the implementation of ObjCInterfaceDecl.
1074void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1075 ObjCImplementationDecl *ImplD) {
1076 assert(IFaceD && ImplD && "Passed null params");
1077 ObjCImpls[IFaceD] = ImplD;
1078}
1079/// \brief Set the implementation of ObjCCategoryDecl.
1080void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1081 ObjCCategoryImplDecl *ImplD) {
1082 assert(CatD && ImplD && "Passed null params");
1083 ObjCImpls[CatD] = ImplD;
1084}
1085
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001086/// \brief Get the copy initialization expression of VarDecl,or NULL if
1087/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001088Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001089 assert(VD && "Passed null params");
1090 assert(VD->hasAttr<BlocksAttr>() &&
1091 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001092 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001093 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001094 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1095}
1096
1097/// \brief Set the copy inialization expression of a block var decl.
1098void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1099 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001100 assert(VD->hasAttr<BlocksAttr>() &&
1101 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001102 BlockVarCopyInits[VD] = Init;
1103}
1104
John McCallbcd03502009-12-07 02:54:59 +00001105/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001106///
John McCallbcd03502009-12-07 02:54:59 +00001107/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001108/// the TypeLoc wrappers.
1109///
1110/// \param T the type that will be the basis for type source info. This type
1111/// should refer to how the declarator was written in source code, not to
1112/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001113TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001114 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001115 if (!DataSize)
1116 DataSize = TypeLoc::getFullDataSizeForType(T);
1117 else
1118 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001119 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001120
John McCallbcd03502009-12-07 02:54:59 +00001121 TypeSourceInfo *TInfo =
1122 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1123 new (TInfo) TypeSourceInfo(T);
1124 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001125}
1126
John McCallbcd03502009-12-07 02:54:59 +00001127TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001128 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001129 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001130 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001131 return DI;
1132}
1133
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001134const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001135ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001136 return getObjCLayout(D, 0);
1137}
1138
1139const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001140ASTContext::getASTObjCImplementationLayout(
1141 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001142 return getObjCLayout(D->getClassInterface(), D);
1143}
1144
Chris Lattner983a8bb2007-07-13 22:13:22 +00001145//===----------------------------------------------------------------------===//
1146// Type creation/memoization methods
1147//===----------------------------------------------------------------------===//
1148
Jay Foad39c79802011-01-12 09:06:06 +00001149QualType
John McCall33ddac02011-01-19 10:06:00 +00001150ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1151 unsigned fastQuals = quals.getFastQualifiers();
1152 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001153
1154 // Check if we've already instantiated this type.
1155 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001156 ExtQuals::Profile(ID, baseType, quals);
1157 void *insertPos = 0;
1158 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1159 assert(eq->getQualifiers() == quals);
1160 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001161 }
1162
John McCall33ddac02011-01-19 10:06:00 +00001163 // If the base type is not canonical, make the appropriate canonical type.
1164 QualType canon;
1165 if (!baseType->isCanonicalUnqualified()) {
1166 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1167 canonSplit.second.addConsistentQualifiers(quals);
1168 canon = getExtQualType(canonSplit.first, canonSplit.second);
1169
1170 // Re-find the insert position.
1171 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1172 }
1173
1174 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1175 ExtQualNodes.InsertNode(eq, insertPos);
1176 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001177}
1178
Jay Foad39c79802011-01-12 09:06:06 +00001179QualType
1180ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001181 QualType CanT = getCanonicalType(T);
1182 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001183 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001184
John McCall8ccfcb52009-09-24 19:53:00 +00001185 // If we are composing extended qualifiers together, merge together
1186 // into one ExtQuals node.
1187 QualifierCollector Quals;
1188 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001189
John McCall8ccfcb52009-09-24 19:53:00 +00001190 // If this type already has an address space specified, it cannot get
1191 // another one.
1192 assert(!Quals.hasAddressSpace() &&
1193 "Type cannot be in multiple addr spaces!");
1194 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001195
John McCall8ccfcb52009-09-24 19:53:00 +00001196 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001197}
1198
Chris Lattnerd60183d2009-02-18 22:53:11 +00001199QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001200 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001201 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001202 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001203 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001204
John McCall53fa7142010-12-24 02:08:15 +00001205 if (const PointerType *ptr = T->getAs<PointerType>()) {
1206 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001207 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001208 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1209 return getPointerType(ResultType);
1210 }
1211 }
Mike Stump11289f42009-09-09 15:08:12 +00001212
John McCall8ccfcb52009-09-24 19:53:00 +00001213 // If we are composing extended qualifiers together, merge together
1214 // into one ExtQuals node.
1215 QualifierCollector Quals;
1216 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001217
John McCall8ccfcb52009-09-24 19:53:00 +00001218 // If this type already has an ObjCGC specified, it cannot get
1219 // another one.
1220 assert(!Quals.hasObjCGCAttr() &&
1221 "Type cannot have multiple ObjCGCs!");
1222 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001223
John McCall8ccfcb52009-09-24 19:53:00 +00001224 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001225}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001226
John McCall4f5019e2010-12-19 02:44:49 +00001227const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1228 FunctionType::ExtInfo Info) {
1229 if (T->getExtInfo() == Info)
1230 return T;
1231
1232 QualType Result;
1233 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1234 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1235 } else {
1236 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1237 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1238 EPI.ExtInfo = Info;
1239 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1240 FPT->getNumArgs(), EPI);
1241 }
1242
1243 return cast<FunctionType>(Result.getTypePtr());
1244}
1245
Chris Lattnerc6395932007-06-22 20:56:16 +00001246/// getComplexType - Return the uniqued reference to the type for a complex
1247/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001248QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001249 // Unique pointers, to guarantee there is only one pointer of a particular
1250 // structure.
1251 llvm::FoldingSetNodeID ID;
1252 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001253
Chris Lattnerc6395932007-06-22 20:56:16 +00001254 void *InsertPos = 0;
1255 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1256 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001257
Chris Lattnerc6395932007-06-22 20:56:16 +00001258 // If the pointee type isn't canonical, this won't be a canonical type either,
1259 // so fill in the canonical type field.
1260 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001261 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001262 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001263
Chris Lattnerc6395932007-06-22 20:56:16 +00001264 // Get the new insert position for the node we care about.
1265 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001266 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001267 }
John McCall90d1c2d2009-09-24 23:30:46 +00001268 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001269 Types.push_back(New);
1270 ComplexTypes.InsertNode(New, InsertPos);
1271 return QualType(New, 0);
1272}
1273
Chris Lattner970e54e2006-11-12 00:37:36 +00001274/// getPointerType - Return the uniqued reference to the type for a pointer to
1275/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001276QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001277 // Unique pointers, to guarantee there is only one pointer of a particular
1278 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001279 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001280 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001281
Chris Lattner67521df2007-01-27 01:29:36 +00001282 void *InsertPos = 0;
1283 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001284 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001285
Chris Lattner7ccecb92006-11-12 08:50:50 +00001286 // If the pointee type isn't canonical, this won't be a canonical type either,
1287 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001288 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001289 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001290 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001291
Chris Lattner67521df2007-01-27 01:29:36 +00001292 // Get the new insert position for the node we care about.
1293 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001294 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001295 }
John McCall90d1c2d2009-09-24 23:30:46 +00001296 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001297 Types.push_back(New);
1298 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001299 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001300}
1301
Mike Stump11289f42009-09-09 15:08:12 +00001302/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001303/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001304QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001305 assert(T->isFunctionType() && "block of function types only");
1306 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001307 // structure.
1308 llvm::FoldingSetNodeID ID;
1309 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001310
Steve Naroffec33ed92008-08-27 16:04:49 +00001311 void *InsertPos = 0;
1312 if (BlockPointerType *PT =
1313 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1314 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001315
1316 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001317 // type either so fill in the canonical type field.
1318 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001319 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001320 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001321
Steve Naroffec33ed92008-08-27 16:04:49 +00001322 // Get the new insert position for the node we care about.
1323 BlockPointerType *NewIP =
1324 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001325 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001326 }
John McCall90d1c2d2009-09-24 23:30:46 +00001327 BlockPointerType *New
1328 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001329 Types.push_back(New);
1330 BlockPointerTypes.InsertNode(New, InsertPos);
1331 return QualType(New, 0);
1332}
1333
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001334/// getLValueReferenceType - Return the uniqued reference to the type for an
1335/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001336QualType
1337ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001338 // Unique pointers, to guarantee there is only one pointer of a particular
1339 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001340 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001341 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001342
1343 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001344 if (LValueReferenceType *RT =
1345 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001346 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001347
John McCallfc93cf92009-10-22 22:37:11 +00001348 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1349
Bill Wendling3708c182007-05-27 10:15:43 +00001350 // If the referencee type isn't canonical, this won't be a canonical type
1351 // either, so fill in the canonical type field.
1352 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001353 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1354 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1355 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001356
Bill Wendling3708c182007-05-27 10:15:43 +00001357 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001358 LValueReferenceType *NewIP =
1359 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001360 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001361 }
1362
John McCall90d1c2d2009-09-24 23:30:46 +00001363 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001364 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1365 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001366 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001367 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001368
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001369 return QualType(New, 0);
1370}
1371
1372/// getRValueReferenceType - Return the uniqued reference to the type for an
1373/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001374QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001375 // Unique pointers, to guarantee there is only one pointer of a particular
1376 // structure.
1377 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001378 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001379
1380 void *InsertPos = 0;
1381 if (RValueReferenceType *RT =
1382 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1383 return QualType(RT, 0);
1384
John McCallfc93cf92009-10-22 22:37:11 +00001385 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1386
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001387 // If the referencee type isn't canonical, this won't be a canonical type
1388 // either, so fill in the canonical type field.
1389 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001390 if (InnerRef || !T.isCanonical()) {
1391 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1392 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001393
1394 // Get the new insert position for the node we care about.
1395 RValueReferenceType *NewIP =
1396 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001397 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001398 }
1399
John McCall90d1c2d2009-09-24 23:30:46 +00001400 RValueReferenceType *New
1401 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001402 Types.push_back(New);
1403 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001404 return QualType(New, 0);
1405}
1406
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001407/// getMemberPointerType - Return the uniqued reference to the type for a
1408/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001409QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001410 // Unique pointers, to guarantee there is only one pointer of a particular
1411 // structure.
1412 llvm::FoldingSetNodeID ID;
1413 MemberPointerType::Profile(ID, T, Cls);
1414
1415 void *InsertPos = 0;
1416 if (MemberPointerType *PT =
1417 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1418 return QualType(PT, 0);
1419
1420 // If the pointee or class type isn't canonical, this won't be a canonical
1421 // type either, so fill in the canonical type field.
1422 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001423 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001424 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1425
1426 // Get the new insert position for the node we care about.
1427 MemberPointerType *NewIP =
1428 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001429 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001430 }
John McCall90d1c2d2009-09-24 23:30:46 +00001431 MemberPointerType *New
1432 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001433 Types.push_back(New);
1434 MemberPointerTypes.InsertNode(New, InsertPos);
1435 return QualType(New, 0);
1436}
1437
Mike Stump11289f42009-09-09 15:08:12 +00001438/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001439/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001440QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001441 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001442 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001443 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001444 assert((EltTy->isDependentType() ||
1445 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001446 "Constant array of VLAs is illegal!");
1447
Chris Lattnere2df3f92009-05-13 04:12:56 +00001448 // Convert the array size into a canonical width matching the pointer size for
1449 // the target.
1450 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001451 ArySize =
1452 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump11289f42009-09-09 15:08:12 +00001453
Chris Lattner23b7eb62007-06-15 23:05:46 +00001454 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001455 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001456
Chris Lattner36f8e652007-01-27 08:31:04 +00001457 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001458 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001459 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001460 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001461
John McCall33ddac02011-01-19 10:06:00 +00001462 // If the element type isn't canonical or has qualifiers, this won't
1463 // be a canonical type either, so fill in the canonical type field.
1464 QualType Canon;
1465 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1466 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1467 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001468 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001469 Canon = getQualifiedType(Canon, canonSplit.second);
1470
Chris Lattner36f8e652007-01-27 08:31:04 +00001471 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001472 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001473 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001474 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
John McCall90d1c2d2009-09-24 23:30:46 +00001477 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001478 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001479 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001480 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001481 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001482}
1483
John McCall06549462011-01-18 08:40:38 +00001484/// getVariableArrayDecayedType - Turns the given type, which may be
1485/// variably-modified, into the corresponding type with all the known
1486/// sizes replaced with [*].
1487QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1488 // Vastly most common case.
1489 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001490
John McCall06549462011-01-18 08:40:38 +00001491 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001492
John McCall06549462011-01-18 08:40:38 +00001493 SplitQualType split = type.getSplitDesugaredType();
1494 const Type *ty = split.first;
1495 switch (ty->getTypeClass()) {
1496#define TYPE(Class, Base)
1497#define ABSTRACT_TYPE(Class, Base)
1498#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1499#include "clang/AST/TypeNodes.def"
1500 llvm_unreachable("didn't desugar past all non-canonical types?");
1501
1502 // These types should never be variably-modified.
1503 case Type::Builtin:
1504 case Type::Complex:
1505 case Type::Vector:
1506 case Type::ExtVector:
1507 case Type::DependentSizedExtVector:
1508 case Type::ObjCObject:
1509 case Type::ObjCInterface:
1510 case Type::ObjCObjectPointer:
1511 case Type::Record:
1512 case Type::Enum:
1513 case Type::UnresolvedUsing:
1514 case Type::TypeOfExpr:
1515 case Type::TypeOf:
1516 case Type::Decltype:
1517 case Type::DependentName:
1518 case Type::InjectedClassName:
1519 case Type::TemplateSpecialization:
1520 case Type::DependentTemplateSpecialization:
1521 case Type::TemplateTypeParm:
1522 case Type::SubstTemplateTypeParmPack:
1523 case Type::PackExpansion:
1524 llvm_unreachable("type should never be variably-modified");
1525
1526 // These types can be variably-modified but should never need to
1527 // further decay.
1528 case Type::FunctionNoProto:
1529 case Type::FunctionProto:
1530 case Type::BlockPointer:
1531 case Type::MemberPointer:
1532 return type;
1533
1534 // These types can be variably-modified. All these modifications
1535 // preserve structure except as noted by comments.
1536 // TODO: if we ever care about optimizing VLAs, there are no-op
1537 // optimizations available here.
1538 case Type::Pointer:
1539 result = getPointerType(getVariableArrayDecayedType(
1540 cast<PointerType>(ty)->getPointeeType()));
1541 break;
1542
1543 case Type::LValueReference: {
1544 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1545 result = getLValueReferenceType(
1546 getVariableArrayDecayedType(lv->getPointeeType()),
1547 lv->isSpelledAsLValue());
1548 break;
1549 }
1550
1551 case Type::RValueReference: {
1552 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1553 result = getRValueReferenceType(
1554 getVariableArrayDecayedType(lv->getPointeeType()));
1555 break;
1556 }
1557
1558 case Type::ConstantArray: {
1559 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1560 result = getConstantArrayType(
1561 getVariableArrayDecayedType(cat->getElementType()),
1562 cat->getSize(),
1563 cat->getSizeModifier(),
1564 cat->getIndexTypeCVRQualifiers());
1565 break;
1566 }
1567
1568 case Type::DependentSizedArray: {
1569 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1570 result = getDependentSizedArrayType(
1571 getVariableArrayDecayedType(dat->getElementType()),
1572 dat->getSizeExpr(),
1573 dat->getSizeModifier(),
1574 dat->getIndexTypeCVRQualifiers(),
1575 dat->getBracketsRange());
1576 break;
1577 }
1578
1579 // Turn incomplete types into [*] types.
1580 case Type::IncompleteArray: {
1581 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1582 result = getVariableArrayType(
1583 getVariableArrayDecayedType(iat->getElementType()),
1584 /*size*/ 0,
1585 ArrayType::Normal,
1586 iat->getIndexTypeCVRQualifiers(),
1587 SourceRange());
1588 break;
1589 }
1590
1591 // Turn VLA types into [*] types.
1592 case Type::VariableArray: {
1593 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1594 result = getVariableArrayType(
1595 getVariableArrayDecayedType(vat->getElementType()),
1596 /*size*/ 0,
1597 ArrayType::Star,
1598 vat->getIndexTypeCVRQualifiers(),
1599 vat->getBracketsRange());
1600 break;
1601 }
1602 }
1603
1604 // Apply the top-level qualifiers from the original.
1605 return getQualifiedType(result, split.second);
1606}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001607
Steve Naroffcadebd02007-08-30 18:14:25 +00001608/// getVariableArrayType - Returns a non-unique reference to the type for a
1609/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001610QualType ASTContext::getVariableArrayType(QualType EltTy,
1611 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001612 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001613 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001614 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001615 // Since we don't unique expressions, it isn't possible to unique VLA's
1616 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001617 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001618
John McCall33ddac02011-01-19 10:06:00 +00001619 // Be sure to pull qualifiers off the element type.
1620 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1621 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1622 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001623 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001624 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001625 }
1626
John McCall90d1c2d2009-09-24 23:30:46 +00001627 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001628 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001629
1630 VariableArrayTypes.push_back(New);
1631 Types.push_back(New);
1632 return QualType(New, 0);
1633}
1634
Douglas Gregor4619e432008-12-05 23:32:09 +00001635/// getDependentSizedArrayType - Returns a non-unique reference to
1636/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001637/// type.
John McCall33ddac02011-01-19 10:06:00 +00001638QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1639 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001640 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001641 unsigned elementTypeQuals,
1642 SourceRange brackets) const {
1643 assert((!numElements || numElements->isTypeDependent() ||
1644 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001645 "Size must be type- or value-dependent!");
1646
John McCall33ddac02011-01-19 10:06:00 +00001647 // Dependently-sized array types that do not have a specified number
1648 // of elements will have their sizes deduced from a dependent
1649 // initializer. We do no canonicalization here at all, which is okay
1650 // because they can't be used in most locations.
1651 if (!numElements) {
1652 DependentSizedArrayType *newType
1653 = new (*this, TypeAlignment)
1654 DependentSizedArrayType(*this, elementType, QualType(),
1655 numElements, ASM, elementTypeQuals,
1656 brackets);
1657 Types.push_back(newType);
1658 return QualType(newType, 0);
1659 }
1660
1661 // Otherwise, we actually build a new type every time, but we
1662 // also build a canonical type.
1663
1664 SplitQualType canonElementType = getCanonicalType(elementType).split();
1665
1666 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001667 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001668 DependentSizedArrayType::Profile(ID, *this,
1669 QualType(canonElementType.first, 0),
1670 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001671
John McCall33ddac02011-01-19 10:06:00 +00001672 // Look for an existing type with these properties.
1673 DependentSizedArrayType *canonTy =
1674 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001675
John McCall33ddac02011-01-19 10:06:00 +00001676 // If we don't have one, build one.
1677 if (!canonTy) {
1678 canonTy = new (*this, TypeAlignment)
1679 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1680 QualType(), numElements, ASM, elementTypeQuals,
1681 brackets);
1682 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1683 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001684 }
1685
John McCall33ddac02011-01-19 10:06:00 +00001686 // Apply qualifiers from the element type to the array.
1687 QualType canon = getQualifiedType(QualType(canonTy,0),
1688 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001689
John McCall33ddac02011-01-19 10:06:00 +00001690 // If we didn't need extra canonicalization for the element type,
1691 // then just use that as our result.
1692 if (QualType(canonElementType.first, 0) == elementType)
1693 return canon;
1694
1695 // Otherwise, we need to build a type which follows the spelling
1696 // of the element type.
1697 DependentSizedArrayType *sugaredType
1698 = new (*this, TypeAlignment)
1699 DependentSizedArrayType(*this, elementType, canon, numElements,
1700 ASM, elementTypeQuals, brackets);
1701 Types.push_back(sugaredType);
1702 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001703}
1704
John McCall33ddac02011-01-19 10:06:00 +00001705QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001706 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001707 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001708 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001709 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001710
John McCall33ddac02011-01-19 10:06:00 +00001711 void *insertPos = 0;
1712 if (IncompleteArrayType *iat =
1713 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1714 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001715
1716 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001717 // either, so fill in the canonical type field. We also have to pull
1718 // qualifiers off the element type.
1719 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001720
John McCall33ddac02011-01-19 10:06:00 +00001721 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1722 SplitQualType canonSplit = getCanonicalType(elementType).split();
1723 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1724 ASM, elementTypeQuals);
1725 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001726
1727 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001728 IncompleteArrayType *existing =
1729 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1730 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001731 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001732
John McCall33ddac02011-01-19 10:06:00 +00001733 IncompleteArrayType *newType = new (*this, TypeAlignment)
1734 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001735
John McCall33ddac02011-01-19 10:06:00 +00001736 IncompleteArrayTypes.InsertNode(newType, insertPos);
1737 Types.push_back(newType);
1738 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001739}
1740
Steve Naroff91fcddb2007-07-18 18:00:27 +00001741/// getVectorType - Return the unique reference to a vector type of
1742/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001743QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001744 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001745 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001746
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001747 // Check if we've already instantiated a vector of this type.
1748 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001749 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001750
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001751 void *InsertPos = 0;
1752 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1753 return QualType(VTP, 0);
1754
1755 // If the element type isn't canonical, this won't be a canonical type either,
1756 // so fill in the canonical type field.
1757 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001758 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001759 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001760
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001761 // Get the new insert position for the node we care about.
1762 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001763 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001764 }
John McCall90d1c2d2009-09-24 23:30:46 +00001765 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001766 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001767 VectorTypes.InsertNode(New, InsertPos);
1768 Types.push_back(New);
1769 return QualType(New, 0);
1770}
1771
Nate Begemance4d7fc2008-04-18 23:10:10 +00001772/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001773/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001774QualType
1775ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall33ddac02011-01-19 10:06:00 +00001776 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001777
Steve Naroff91fcddb2007-07-18 18:00:27 +00001778 // Check if we've already instantiated a vector of this type.
1779 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001780 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001781 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001782 void *InsertPos = 0;
1783 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1784 return QualType(VTP, 0);
1785
1786 // If the element type isn't canonical, this won't be a canonical type either,
1787 // so fill in the canonical type field.
1788 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001789 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001790 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001791
Steve Naroff91fcddb2007-07-18 18:00:27 +00001792 // Get the new insert position for the node we care about.
1793 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001794 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001795 }
John McCall90d1c2d2009-09-24 23:30:46 +00001796 ExtVectorType *New = new (*this, TypeAlignment)
1797 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001798 VectorTypes.InsertNode(New, InsertPos);
1799 Types.push_back(New);
1800 return QualType(New, 0);
1801}
1802
Jay Foad39c79802011-01-12 09:06:06 +00001803QualType
1804ASTContext::getDependentSizedExtVectorType(QualType vecType,
1805 Expr *SizeExpr,
1806 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001807 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001808 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001809 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001810
Douglas Gregor352169a2009-07-31 03:54:25 +00001811 void *InsertPos = 0;
1812 DependentSizedExtVectorType *Canon
1813 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1814 DependentSizedExtVectorType *New;
1815 if (Canon) {
1816 // We already have a canonical version of this array type; use it as
1817 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001818 New = new (*this, TypeAlignment)
1819 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1820 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001821 } else {
1822 QualType CanonVecTy = getCanonicalType(vecType);
1823 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001824 New = new (*this, TypeAlignment)
1825 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1826 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001827
1828 DependentSizedExtVectorType *CanonCheck
1829 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1830 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1831 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001832 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1833 } else {
1834 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1835 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001836 New = new (*this, TypeAlignment)
1837 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001838 }
1839 }
Mike Stump11289f42009-09-09 15:08:12 +00001840
Douglas Gregor758a8692009-06-17 21:51:59 +00001841 Types.push_back(New);
1842 return QualType(New, 0);
1843}
1844
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001845/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001846///
Jay Foad39c79802011-01-12 09:06:06 +00001847QualType
1848ASTContext::getFunctionNoProtoType(QualType ResultTy,
1849 const FunctionType::ExtInfo &Info) const {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001850 const CallingConv CallConv = Info.getCC();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001851 // Unique functions, to guarantee there is only one function of a particular
1852 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001853 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001854 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001855
Chris Lattner47955de2007-01-27 08:37:20 +00001856 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001857 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001858 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001859 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001860
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001861 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001862 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001863 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001864 Canonical =
1865 getFunctionNoProtoType(getCanonicalType(ResultTy),
1866 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001867
Chris Lattner47955de2007-01-27 08:37:20 +00001868 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001869 FunctionNoProtoType *NewIP =
1870 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001871 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001872 }
Mike Stump11289f42009-09-09 15:08:12 +00001873
John McCall90d1c2d2009-09-24 23:30:46 +00001874 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001875 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00001876 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001877 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001878 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001879}
1880
1881/// getFunctionType - Return a normal function type with a typed argument
1882/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001883QualType
1884ASTContext::getFunctionType(QualType ResultTy,
1885 const QualType *ArgArray, unsigned NumArgs,
1886 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001887 // Unique functions, to guarantee there is only one function of a particular
1888 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001889 llvm::FoldingSetNodeID ID;
John McCalldb40c7f2010-12-14 08:05:40 +00001890 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001891
1892 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001893 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001894 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001895 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001896
1897 // Determine whether the type being created is already canonical or not.
John McCalldb40c7f2010-12-14 08:05:40 +00001898 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001899 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001900 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001901 isCanonical = false;
1902
John McCalldb40c7f2010-12-14 08:05:40 +00001903 const CallingConv CallConv = EPI.ExtInfo.getCC();
1904
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001905 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001906 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001907 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001908 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001909 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001910 CanonicalArgs.reserve(NumArgs);
1911 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001912 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001913
John McCalldb40c7f2010-12-14 08:05:40 +00001914 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
1915 if (CanonicalEPI.HasExceptionSpec) {
1916 CanonicalEPI.HasExceptionSpec = false;
1917 CanonicalEPI.HasAnyExceptionSpec = false;
1918 CanonicalEPI.NumExceptions = 0;
1919 }
1920 CanonicalEPI.ExtInfo
1921 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1922
Chris Lattner76a00cf2008-04-06 22:59:24 +00001923 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001924 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001925 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001926
Chris Lattnerfd4de792007-01-27 01:15:32 +00001927 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001928 FunctionProtoType *NewIP =
1929 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001930 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001931 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001932
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001933 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001934 // for two variable size arrays (for parameter and exception types) at the
1935 // end of them.
John McCalldb40c7f2010-12-14 08:05:40 +00001936 size_t Size = sizeof(FunctionProtoType) +
1937 NumArgs * sizeof(QualType) +
1938 EPI.NumExceptions * sizeof(QualType);
1939 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
1940 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, EPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001941 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001942 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001943 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001944}
Chris Lattneref51c202006-11-10 07:17:23 +00001945
John McCalle78aac42010-03-10 03:28:59 +00001946#ifndef NDEBUG
1947static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1948 if (!isa<CXXRecordDecl>(D)) return false;
1949 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1950 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1951 return true;
1952 if (RD->getDescribedClassTemplate() &&
1953 !isa<ClassTemplateSpecializationDecl>(RD))
1954 return true;
1955 return false;
1956}
1957#endif
1958
1959/// getInjectedClassNameType - Return the unique reference to the
1960/// injected class name type for the specified templated declaration.
1961QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00001962 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00001963 assert(NeedsInjectedClassNameType(Decl));
1964 if (Decl->TypeForDecl) {
1965 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00001966 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00001967 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1968 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1969 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1970 } else {
John McCall424cec92011-01-19 06:33:43 +00001971 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00001972 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00001973 Decl->TypeForDecl = newType;
1974 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00001975 }
1976 return QualType(Decl->TypeForDecl, 0);
1977}
1978
Douglas Gregor83a586e2008-04-13 21:07:44 +00001979/// getTypeDeclType - Return the unique reference to the type for the
1980/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00001981QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00001982 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00001983 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00001984
John McCall81e38502010-02-16 03:57:14 +00001985 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00001986 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00001987
John McCall96f0b5f2010-03-10 06:48:02 +00001988 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1989 "Template type parameter types are always available.");
1990
John McCall81e38502010-02-16 03:57:14 +00001991 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001992 assert(!Record->getPreviousDeclaration() &&
1993 "struct/union has previous declaration");
1994 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001995 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00001996 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00001997 assert(!Enum->getPreviousDeclaration() &&
1998 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00001999 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002000 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002001 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002002 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2003 Decl->TypeForDecl = newType;
2004 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002005 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002006 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002007
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002008 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002009}
2010
Chris Lattner32d920b2007-01-26 02:01:53 +00002011/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00002012/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002013QualType
Jay Foad39c79802011-01-12 09:06:06 +00002014ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002015 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002016
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002017 if (Canonical.isNull())
2018 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002019 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002020 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002021 Decl->TypeForDecl = newType;
2022 Types.push_back(newType);
2023 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002024}
2025
Jay Foad39c79802011-01-12 09:06:06 +00002026QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002027 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2028
2029 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2030 if (PrevDecl->TypeForDecl)
2031 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2032
John McCall424cec92011-01-19 06:33:43 +00002033 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2034 Decl->TypeForDecl = newType;
2035 Types.push_back(newType);
2036 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002037}
2038
Jay Foad39c79802011-01-12 09:06:06 +00002039QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002040 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2041
2042 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2043 if (PrevDecl->TypeForDecl)
2044 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2045
John McCall424cec92011-01-19 06:33:43 +00002046 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2047 Decl->TypeForDecl = newType;
2048 Types.push_back(newType);
2049 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002050}
2051
John McCall81904512011-01-06 01:58:22 +00002052QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2053 QualType modifiedType,
2054 QualType equivalentType) {
2055 llvm::FoldingSetNodeID id;
2056 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2057
2058 void *insertPos = 0;
2059 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2060 if (type) return QualType(type, 0);
2061
2062 QualType canon = getCanonicalType(equivalentType);
2063 type = new (*this, TypeAlignment)
2064 AttributedType(canon, attrKind, modifiedType, equivalentType);
2065
2066 Types.push_back(type);
2067 AttributedTypes.InsertNode(type, insertPos);
2068
2069 return QualType(type, 0);
2070}
2071
2072
John McCallcebee162009-10-18 09:09:24 +00002073/// \brief Retrieve a substitution-result type.
2074QualType
2075ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002076 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002077 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002078 && "replacement types must always be canonical");
2079
2080 llvm::FoldingSetNodeID ID;
2081 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2082 void *InsertPos = 0;
2083 SubstTemplateTypeParmType *SubstParm
2084 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2085
2086 if (!SubstParm) {
2087 SubstParm = new (*this, TypeAlignment)
2088 SubstTemplateTypeParmType(Parm, Replacement);
2089 Types.push_back(SubstParm);
2090 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2091 }
2092
2093 return QualType(SubstParm, 0);
2094}
2095
Douglas Gregorada4b792011-01-14 02:55:32 +00002096/// \brief Retrieve a
2097QualType ASTContext::getSubstTemplateTypeParmPackType(
2098 const TemplateTypeParmType *Parm,
2099 const TemplateArgument &ArgPack) {
2100#ifndef NDEBUG
2101 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2102 PEnd = ArgPack.pack_end();
2103 P != PEnd; ++P) {
2104 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2105 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2106 }
2107#endif
2108
2109 llvm::FoldingSetNodeID ID;
2110 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2111 void *InsertPos = 0;
2112 if (SubstTemplateTypeParmPackType *SubstParm
2113 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2114 return QualType(SubstParm, 0);
2115
2116 QualType Canon;
2117 if (!Parm->isCanonicalUnqualified()) {
2118 Canon = getCanonicalType(QualType(Parm, 0));
2119 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2120 ArgPack);
2121 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2122 }
2123
2124 SubstTemplateTypeParmPackType *SubstParm
2125 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2126 ArgPack);
2127 Types.push_back(SubstParm);
2128 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2129 return QualType(SubstParm, 0);
2130}
2131
Douglas Gregoreff93e02009-02-05 23:33:38 +00002132/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002133/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002134/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002135QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002136 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00002137 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002138 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002139 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002140 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002141 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002142 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2143
2144 if (TypeParm)
2145 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002146
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002147 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002148 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002149 TypeParm = new (*this, TypeAlignment)
2150 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002151
2152 TemplateTypeParmType *TypeCheck
2153 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2154 assert(!TypeCheck && "Template type parameter canonical type broken");
2155 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002156 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002157 TypeParm = new (*this, TypeAlignment)
2158 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002159
2160 Types.push_back(TypeParm);
2161 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2162
2163 return QualType(TypeParm, 0);
2164}
2165
John McCalle78aac42010-03-10 03:28:59 +00002166TypeSourceInfo *
2167ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2168 SourceLocation NameLoc,
2169 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002170 QualType CanonType) const {
John McCalle78aac42010-03-10 03:28:59 +00002171 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2172
2173 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2174 TemplateSpecializationTypeLoc TL
2175 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2176 TL.setTemplateNameLoc(NameLoc);
2177 TL.setLAngleLoc(Args.getLAngleLoc());
2178 TL.setRAngleLoc(Args.getRAngleLoc());
2179 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2180 TL.setArgLocInfo(i, Args[i].getLocInfo());
2181 return DI;
2182}
2183
Mike Stump11289f42009-09-09 15:08:12 +00002184QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002185ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002186 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002187 QualType Canon) const {
John McCall6b51f282009-11-23 01:53:49 +00002188 unsigned NumArgs = Args.size();
2189
John McCall0ad16662009-10-29 08:12:44 +00002190 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2191 ArgVec.reserve(NumArgs);
2192 for (unsigned i = 0; i != NumArgs; ++i)
2193 ArgVec.push_back(Args[i].getArgument());
2194
John McCall2408e322010-04-27 00:57:59 +00002195 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002196 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002197}
2198
2199QualType
2200ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002201 const TemplateArgument *Args,
2202 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002203 QualType Canon) const {
Douglas Gregor15301382009-07-30 17:40:51 +00002204 if (!Canon.isNull())
2205 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002206 else
2207 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002208
Douglas Gregora8e02e72009-07-28 23:00:59 +00002209 // Allocate the (non-canonical) template specialization type, but don't
2210 // try to unique it: these types typically have location information that
2211 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002212 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002213 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002214 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002215 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002216 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002217 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002218 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002219
Douglas Gregor8bf42052009-02-09 18:46:07 +00002220 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002221 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002222}
2223
Mike Stump11289f42009-09-09 15:08:12 +00002224QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002225ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2226 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002227 unsigned NumArgs) const {
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002228 // Build the canonical template specialization type.
2229 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2230 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2231 CanonArgs.reserve(NumArgs);
2232 for (unsigned I = 0; I != NumArgs; ++I)
2233 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2234
2235 // Determine whether this canonical template specialization type already
2236 // exists.
2237 llvm::FoldingSetNodeID ID;
2238 TemplateSpecializationType::Profile(ID, CanonTemplate,
2239 CanonArgs.data(), NumArgs, *this);
2240
2241 void *InsertPos = 0;
2242 TemplateSpecializationType *Spec
2243 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2244
2245 if (!Spec) {
2246 // Allocate a new canonical template specialization type.
2247 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2248 sizeof(TemplateArgument) * NumArgs),
2249 TypeAlignment);
2250 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2251 CanonArgs.data(), NumArgs,
2252 QualType());
2253 Types.push_back(Spec);
2254 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2255 }
2256
2257 assert(Spec->isDependentType() &&
2258 "Non-dependent template-id type must have a canonical type");
2259 return QualType(Spec, 0);
2260}
2261
2262QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002263ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2264 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002265 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002266 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002267 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002268
2269 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002270 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002271 if (T)
2272 return QualType(T, 0);
2273
Douglas Gregorc42075a2010-02-04 18:10:26 +00002274 QualType Canon = NamedType;
2275 if (!Canon.isCanonical()) {
2276 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002277 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2278 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002279 (void)CheckT;
2280 }
2281
Abramo Bagnara6150c882010-05-11 21:36:43 +00002282 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002283 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002284 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002285 return QualType(T, 0);
2286}
2287
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002288QualType
Jay Foad39c79802011-01-12 09:06:06 +00002289ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002290 llvm::FoldingSetNodeID ID;
2291 ParenType::Profile(ID, InnerType);
2292
2293 void *InsertPos = 0;
2294 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2295 if (T)
2296 return QualType(T, 0);
2297
2298 QualType Canon = InnerType;
2299 if (!Canon.isCanonical()) {
2300 Canon = getCanonicalType(InnerType);
2301 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2302 assert(!CheckT && "Paren canonical type broken");
2303 (void)CheckT;
2304 }
2305
2306 T = new (*this) ParenType(InnerType, Canon);
2307 Types.push_back(T);
2308 ParenTypes.InsertNode(T, InsertPos);
2309 return QualType(T, 0);
2310}
2311
Douglas Gregor02085352010-03-31 20:19:30 +00002312QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2313 NestedNameSpecifier *NNS,
2314 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002315 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002316 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2317
2318 if (Canon.isNull()) {
2319 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002320 ElaboratedTypeKeyword CanonKeyword = Keyword;
2321 if (Keyword == ETK_None)
2322 CanonKeyword = ETK_Typename;
2323
2324 if (CanonNNS != NNS || CanonKeyword != Keyword)
2325 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002326 }
2327
2328 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002329 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002330
2331 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002332 DependentNameType *T
2333 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002334 if (T)
2335 return QualType(T, 0);
2336
Douglas Gregor02085352010-03-31 20:19:30 +00002337 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002338 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002339 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002340 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002341}
2342
Mike Stump11289f42009-09-09 15:08:12 +00002343QualType
John McCallc392f372010-06-11 00:33:02 +00002344ASTContext::getDependentTemplateSpecializationType(
2345 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002346 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002347 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002348 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002349 // TODO: avoid this copy
2350 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2351 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2352 ArgCopy.push_back(Args[I].getArgument());
2353 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2354 ArgCopy.size(),
2355 ArgCopy.data());
2356}
2357
2358QualType
2359ASTContext::getDependentTemplateSpecializationType(
2360 ElaboratedTypeKeyword Keyword,
2361 NestedNameSpecifier *NNS,
2362 const IdentifierInfo *Name,
2363 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002364 const TemplateArgument *Args) const {
Douglas Gregordce2b622009-04-01 00:28:59 +00002365 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2366
Douglas Gregorc42075a2010-02-04 18:10:26 +00002367 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002368 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2369 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002370
2371 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002372 DependentTemplateSpecializationType *T
2373 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002374 if (T)
2375 return QualType(T, 0);
2376
John McCallc392f372010-06-11 00:33:02 +00002377 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002378
John McCallc392f372010-06-11 00:33:02 +00002379 ElaboratedTypeKeyword CanonKeyword = Keyword;
2380 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2381
2382 bool AnyNonCanonArgs = false;
2383 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2384 for (unsigned I = 0; I != NumArgs; ++I) {
2385 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2386 if (!CanonArgs[I].structurallyEquals(Args[I]))
2387 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002388 }
2389
John McCallc392f372010-06-11 00:33:02 +00002390 QualType Canon;
2391 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2392 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2393 Name, NumArgs,
2394 CanonArgs.data());
2395
2396 // Find the insert position again.
2397 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2398 }
2399
2400 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2401 sizeof(TemplateArgument) * NumArgs),
2402 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002403 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002404 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002405 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002406 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002407 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002408}
2409
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002410QualType ASTContext::getPackExpansionType(QualType Pattern,
2411 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002412 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002413 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002414
2415 assert(Pattern->containsUnexpandedParameterPack() &&
2416 "Pack expansions must expand one or more parameter packs");
2417 void *InsertPos = 0;
2418 PackExpansionType *T
2419 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2420 if (T)
2421 return QualType(T, 0);
2422
2423 QualType Canon;
2424 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002425 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002426
2427 // Find the insert position again.
2428 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2429 }
2430
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002431 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002432 Types.push_back(T);
2433 PackExpansionTypes.InsertNode(T, InsertPos);
2434 return QualType(T, 0);
2435}
2436
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002437/// CmpProtocolNames - Comparison predicate for sorting protocols
2438/// alphabetically.
2439static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2440 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002441 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002442}
2443
John McCall8b07ec22010-05-15 11:32:37 +00002444static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002445 unsigned NumProtocols) {
2446 if (NumProtocols == 0) return true;
2447
2448 for (unsigned i = 1; i != NumProtocols; ++i)
2449 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2450 return false;
2451 return true;
2452}
2453
2454static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002455 unsigned &NumProtocols) {
2456 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002457
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002458 // Sort protocols, keyed by name.
2459 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2460
2461 // Remove duplicates.
2462 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2463 NumProtocols = ProtocolsEnd-Protocols;
2464}
2465
John McCall8b07ec22010-05-15 11:32:37 +00002466QualType ASTContext::getObjCObjectType(QualType BaseType,
2467 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002468 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002469 // If the base type is an interface and there aren't any protocols
2470 // to add, then the interface type will do just fine.
2471 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2472 return BaseType;
2473
2474 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002475 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002476 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002477 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002478 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2479 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002480
John McCall8b07ec22010-05-15 11:32:37 +00002481 // Build the canonical type, which has the canonical base type and
2482 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002483 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002484 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2485 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2486 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002487 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2488 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002489 unsigned UniqueCount = NumProtocols;
2490
John McCallfc93cf92009-10-22 22:37:11 +00002491 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002492 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2493 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002494 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002495 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2496 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002497 }
2498
2499 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002500 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2501 }
2502
2503 unsigned Size = sizeof(ObjCObjectTypeImpl);
2504 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2505 void *Mem = Allocate(Size, TypeAlignment);
2506 ObjCObjectTypeImpl *T =
2507 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2508
2509 Types.push_back(T);
2510 ObjCObjectTypes.InsertNode(T, InsertPos);
2511 return QualType(T, 0);
2512}
2513
2514/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2515/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002516QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002517 llvm::FoldingSetNodeID ID;
2518 ObjCObjectPointerType::Profile(ID, ObjectT);
2519
2520 void *InsertPos = 0;
2521 if (ObjCObjectPointerType *QT =
2522 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2523 return QualType(QT, 0);
2524
2525 // Find the canonical object type.
2526 QualType Canonical;
2527 if (!ObjectT.isCanonical()) {
2528 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2529
2530 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002531 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2532 }
2533
Douglas Gregorf85bee62010-02-08 22:59:26 +00002534 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002535 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2536 ObjCObjectPointerType *QType =
2537 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002538
Steve Narofffb4330f2009-06-17 22:40:22 +00002539 Types.push_back(QType);
2540 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002541 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002542}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002543
Douglas Gregor1c283312010-08-11 12:19:30 +00002544/// getObjCInterfaceType - Return the unique reference to the type for the
2545/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002546QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002547 if (Decl->TypeForDecl)
2548 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002549
Douglas Gregor1c283312010-08-11 12:19:30 +00002550 // FIXME: redeclarations?
2551 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2552 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2553 Decl->TypeForDecl = T;
2554 Types.push_back(T);
2555 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002556}
2557
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002558/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2559/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002560/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002561/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002562/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002563QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002564 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002565 if (tofExpr->isTypeDependent()) {
2566 llvm::FoldingSetNodeID ID;
2567 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002568
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002569 void *InsertPos = 0;
2570 DependentTypeOfExprType *Canon
2571 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2572 if (Canon) {
2573 // We already have a "canonical" version of an identical, dependent
2574 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002575 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002576 QualType((TypeOfExprType*)Canon, 0));
2577 }
2578 else {
2579 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002580 Canon
2581 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002582 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2583 toe = Canon;
2584 }
2585 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002586 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002587 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002588 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002589 Types.push_back(toe);
2590 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002591}
2592
Steve Naroffa773cd52007-08-01 18:02:17 +00002593/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2594/// TypeOfType AST's. The only motivation to unique these nodes would be
2595/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002596/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002597/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002598QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002599 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002600 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002601 Types.push_back(tot);
2602 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002603}
2604
Anders Carlssonad6bd352009-06-24 21:24:56 +00002605/// getDecltypeForExpr - Given an expr, will return the decltype for that
2606/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002607static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002608 if (e->isTypeDependent())
2609 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002610
Anders Carlssonad6bd352009-06-24 21:24:56 +00002611 // If e is an id expression or a class member access, decltype(e) is defined
2612 // as the type of the entity named by e.
2613 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2614 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2615 return VD->getType();
2616 }
2617 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2618 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2619 return FD->getType();
2620 }
2621 // If e is a function call or an invocation of an overloaded operator,
2622 // (parentheses around e are ignored), decltype(e) is defined as the
2623 // return type of that function.
2624 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2625 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002626
Anders Carlssonad6bd352009-06-24 21:24:56 +00002627 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002628
2629 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002630 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002631 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002632 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002633
Anders Carlssonad6bd352009-06-24 21:24:56 +00002634 return T;
2635}
2636
Anders Carlsson81df7b82009-06-24 19:06:50 +00002637/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2638/// DecltypeType AST's. The only motivation to unique these nodes would be
2639/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002640/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002641/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002642QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002643 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002644 if (e->isTypeDependent()) {
2645 llvm::FoldingSetNodeID ID;
2646 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002647
Douglas Gregora21f6c32009-07-30 23:36:40 +00002648 void *InsertPos = 0;
2649 DependentDecltypeType *Canon
2650 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2651 if (Canon) {
2652 // We already have a "canonical" version of an equivalent, dependent
2653 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002654 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002655 QualType((DecltypeType*)Canon, 0));
2656 }
2657 else {
2658 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002659 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002660 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2661 dt = Canon;
2662 }
2663 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002664 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002665 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002666 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002667 Types.push_back(dt);
2668 return QualType(dt, 0);
2669}
2670
Chris Lattnerfb072462007-01-23 05:45:31 +00002671/// getTagDeclType - Return the unique reference to the type for the
2672/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002673QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002674 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002675 // FIXME: What is the design on getTagDeclType when it requires casting
2676 // away const? mutable?
2677 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002678}
2679
Mike Stump11289f42009-09-09 15:08:12 +00002680/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2681/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2682/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002683CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002684 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002685}
Chris Lattnerfb072462007-01-23 05:45:31 +00002686
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002687/// getSignedWCharType - Return the type of "signed wchar_t".
2688/// Used when in C++, as a GCC extension.
2689QualType ASTContext::getSignedWCharType() const {
2690 // FIXME: derive from "Target" ?
2691 return WCharTy;
2692}
2693
2694/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2695/// Used when in C++, as a GCC extension.
2696QualType ASTContext::getUnsignedWCharType() const {
2697 // FIXME: derive from "Target" ?
2698 return UnsignedIntTy;
2699}
2700
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002701/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2702/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2703QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002704 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002705}
2706
Chris Lattnera21ad802008-04-02 05:18:44 +00002707//===----------------------------------------------------------------------===//
2708// Type Operators
2709//===----------------------------------------------------------------------===//
2710
Jay Foad39c79802011-01-12 09:06:06 +00002711CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002712 // Push qualifiers into arrays, and then discard any remaining
2713 // qualifiers.
2714 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002715 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002716 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002717 QualType Result;
2718 if (isa<ArrayType>(Ty)) {
2719 Result = getArrayDecayedType(QualType(Ty,0));
2720 } else if (isa<FunctionType>(Ty)) {
2721 Result = getPointerType(QualType(Ty, 0));
2722 } else {
2723 Result = QualType(Ty, 0);
2724 }
2725
2726 return CanQualType::CreateUnsafe(Result);
2727}
2728
Chris Lattner7adf0762008-08-04 07:31:14 +00002729
John McCall6c9dd522011-01-18 07:41:22 +00002730QualType ASTContext::getUnqualifiedArrayType(QualType type,
2731 Qualifiers &quals) {
2732 SplitQualType splitType = type.getSplitUnqualifiedType();
2733
2734 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2735 // the unqualified desugared type and then drops it on the floor.
2736 // We then have to strip that sugar back off with
2737 // getUnqualifiedDesugaredType(), which is silly.
2738 const ArrayType *AT =
2739 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2740
2741 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002742 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002743 quals = splitType.second;
2744 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002745 }
2746
John McCall6c9dd522011-01-18 07:41:22 +00002747 // Otherwise, recurse on the array's element type.
2748 QualType elementType = AT->getElementType();
2749 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2750
2751 // If that didn't change the element type, AT has no qualifiers, so we
2752 // can just use the results in splitType.
2753 if (elementType == unqualElementType) {
2754 assert(quals.empty()); // from the recursive call
2755 quals = splitType.second;
2756 return QualType(splitType.first, 0);
2757 }
2758
2759 // Otherwise, add in the qualifiers from the outermost type, then
2760 // build the type back up.
2761 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002762
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002763 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002764 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002765 CAT->getSizeModifier(), 0);
2766 }
2767
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002768 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002769 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002770 }
2771
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002772 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002773 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002774 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002775 VAT->getSizeModifier(),
2776 VAT->getIndexTypeCVRQualifiers(),
2777 VAT->getBracketsRange());
2778 }
2779
2780 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002781 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002782 DSAT->getSizeModifier(), 0,
2783 SourceRange());
2784}
2785
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002786/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2787/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2788/// they point to and return true. If T1 and T2 aren't pointer types
2789/// or pointer-to-member types, or if they are not similar at this
2790/// level, returns false and leaves T1 and T2 unchanged. Top-level
2791/// qualifiers on T1 and T2 are ignored. This function will typically
2792/// be called in a loop that successively "unwraps" pointer and
2793/// pointer-to-member types to compare them at each level.
2794bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2795 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2796 *T2PtrType = T2->getAs<PointerType>();
2797 if (T1PtrType && T2PtrType) {
2798 T1 = T1PtrType->getPointeeType();
2799 T2 = T2PtrType->getPointeeType();
2800 return true;
2801 }
2802
2803 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2804 *T2MPType = T2->getAs<MemberPointerType>();
2805 if (T1MPType && T2MPType &&
2806 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2807 QualType(T2MPType->getClass(), 0))) {
2808 T1 = T1MPType->getPointeeType();
2809 T2 = T2MPType->getPointeeType();
2810 return true;
2811 }
2812
2813 if (getLangOptions().ObjC1) {
2814 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2815 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2816 if (T1OPType && T2OPType) {
2817 T1 = T1OPType->getPointeeType();
2818 T2 = T2OPType->getPointeeType();
2819 return true;
2820 }
2821 }
2822
2823 // FIXME: Block pointers, too?
2824
2825 return false;
2826}
2827
Jay Foad39c79802011-01-12 09:06:06 +00002828DeclarationNameInfo
2829ASTContext::getNameForTemplate(TemplateName Name,
2830 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002831 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002832 // DNInfo work in progress: CHECKME: what about DNLoc?
2833 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2834
John McCall847e2a12009-11-24 18:42:40 +00002835 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002836 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002837 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002838 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2839 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002840 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002841 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2842 // DNInfo work in progress: FIXME: source locations?
2843 DeclarationNameLoc DNLoc;
2844 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2845 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2846 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002847 }
2848 }
2849
John McCalld28ae272009-12-02 08:04:21 +00002850 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2851 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002852 // DNInfo work in progress: CHECKME: what about DNLoc?
2853 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002854}
2855
Jay Foad39c79802011-01-12 09:06:06 +00002856TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002857 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2858 if (TemplateTemplateParmDecl *TTP
2859 = dyn_cast<TemplateTemplateParmDecl>(Template))
2860 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2861
2862 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002863 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002864 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002865
Douglas Gregor5590be02011-01-15 06:45:20 +00002866 if (SubstTemplateTemplateParmPackStorage *SubstPack
2867 = Name.getAsSubstTemplateTemplateParmPack()) {
2868 TemplateTemplateParmDecl *CanonParam
2869 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2870 TemplateArgument CanonArgPack
2871 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2872 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2873 }
2874
John McCalld28ae272009-12-02 08:04:21 +00002875 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002876
Douglas Gregor6bc50582009-05-07 06:41:52 +00002877 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2878 assert(DTN && "Non-dependent template names must refer to template decls.");
2879 return DTN->CanonicalTemplateName;
2880}
2881
Douglas Gregoradee3e32009-11-11 23:06:43 +00002882bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2883 X = getCanonicalTemplateName(X);
2884 Y = getCanonicalTemplateName(Y);
2885 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2886}
2887
Mike Stump11289f42009-09-09 15:08:12 +00002888TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002889ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002890 switch (Arg.getKind()) {
2891 case TemplateArgument::Null:
2892 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002893
Douglas Gregora8e02e72009-07-28 23:00:59 +00002894 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002895 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002896
Douglas Gregora8e02e72009-07-28 23:00:59 +00002897 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002898 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002899
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002900 case TemplateArgument::Template:
2901 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002902
2903 case TemplateArgument::TemplateExpansion:
2904 return TemplateArgument(getCanonicalTemplateName(
2905 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002906 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002907
Douglas Gregora8e02e72009-07-28 23:00:59 +00002908 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002909 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002910 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002911
Douglas Gregora8e02e72009-07-28 23:00:59 +00002912 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002913 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00002914
Douglas Gregora8e02e72009-07-28 23:00:59 +00002915 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00002916 if (Arg.pack_size() == 0)
2917 return Arg;
2918
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002919 TemplateArgument *CanonArgs
2920 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00002921 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002922 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002923 AEnd = Arg.pack_end();
2924 A != AEnd; (void)++A, ++Idx)
2925 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00002926
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002927 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00002928 }
2929 }
2930
2931 // Silence GCC warning
2932 assert(false && "Unhandled template argument kind");
2933 return TemplateArgument();
2934}
2935
Douglas Gregor333489b2009-03-27 23:10:48 +00002936NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00002937ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00002938 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00002939 return 0;
2940
2941 switch (NNS->getKind()) {
2942 case NestedNameSpecifier::Identifier:
2943 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00002944 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00002945 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2946 NNS->getAsIdentifier());
2947
2948 case NestedNameSpecifier::Namespace:
2949 // A namespace is canonical; build a nested-name-specifier with
2950 // this namespace and no prefix.
2951 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2952
2953 case NestedNameSpecifier::TypeSpec:
2954 case NestedNameSpecifier::TypeSpecWithTemplate: {
2955 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00002956
2957 // If we have some kind of dependent-named type (e.g., "typename T::type"),
2958 // break it apart into its prefix and identifier, then reconsititute those
2959 // as the canonical nested-name-specifier. This is required to canonicalize
2960 // a dependent nested-name-specifier involving typedefs of dependent-name
2961 // types, e.g.,
2962 // typedef typename T::type T1;
2963 // typedef typename T1::type T2;
2964 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
2965 NestedNameSpecifier *Prefix
2966 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
2967 return NestedNameSpecifier::Create(*this, Prefix,
2968 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
2969 }
2970
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00002971 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00002972 if (const DependentTemplateSpecializationType *DTST
2973 = T->getAs<DependentTemplateSpecializationType>()) {
2974 NestedNameSpecifier *Prefix
2975 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
2976 TemplateName Name
2977 = getDependentTemplateName(Prefix, DTST->getIdentifier());
2978 T = getTemplateSpecializationType(Name,
2979 DTST->getArgs(), DTST->getNumArgs());
2980 T = getCanonicalType(T);
2981 }
2982
John McCall33ddac02011-01-19 10:06:00 +00002983 return NestedNameSpecifier::Create(*this, 0, false,
2984 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00002985 }
2986
2987 case NestedNameSpecifier::Global:
2988 // The global specifier is canonical and unique.
2989 return NNS;
2990 }
2991
2992 // Required to silence a GCC warning
2993 return 0;
2994}
2995
Chris Lattner7adf0762008-08-04 07:31:14 +00002996
Jay Foad39c79802011-01-12 09:06:06 +00002997const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00002998 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002999 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003000 // Handle the common positive case fast.
3001 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3002 return AT;
3003 }
Mike Stump11289f42009-09-09 15:08:12 +00003004
John McCall8ccfcb52009-09-24 19:53:00 +00003005 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003006 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003007 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003008
John McCall8ccfcb52009-09-24 19:53:00 +00003009 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003010 // implements C99 6.7.3p8: "If the specification of an array type includes
3011 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003012
Chris Lattner7adf0762008-08-04 07:31:14 +00003013 // If we get here, we either have type qualifiers on the type, or we have
3014 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003015 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003016
John McCall33ddac02011-01-19 10:06:00 +00003017 SplitQualType split = T.getSplitDesugaredType();
3018 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003019
Chris Lattner7adf0762008-08-04 07:31:14 +00003020 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003021 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3022 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003023 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003024
Chris Lattner7adf0762008-08-04 07:31:14 +00003025 // Otherwise, we have an array and we have qualifiers on it. Push the
3026 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003027 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003028
Chris Lattner7adf0762008-08-04 07:31:14 +00003029 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3030 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3031 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003032 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003033 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3034 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3035 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003036 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003037
Mike Stump11289f42009-09-09 15:08:12 +00003038 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003039 = dyn_cast<DependentSizedArrayType>(ATy))
3040 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003041 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003042 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003043 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003044 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003045 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003046
Chris Lattner7adf0762008-08-04 07:31:14 +00003047 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003048 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003049 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003050 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003051 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003052 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003053}
3054
Chris Lattnera21ad802008-04-02 05:18:44 +00003055/// getArrayDecayedType - Return the properly qualified result of decaying the
3056/// specified array type to a pointer. This operation is non-trivial when
3057/// handling typedefs etc. The canonical type of "T" must be an array type,
3058/// this returns a pointer to a properly qualified element of the array.
3059///
3060/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003061QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003062 // Get the element type with 'getAsArrayType' so that we don't lose any
3063 // typedefs in the element type of the array. This also handles propagation
3064 // of type qualifiers from the array type into the element type if present
3065 // (C99 6.7.3p8).
3066 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3067 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003068
Chris Lattner7adf0762008-08-04 07:31:14 +00003069 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003070
3071 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003072 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003073}
3074
John McCall33ddac02011-01-19 10:06:00 +00003075QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3076 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003077}
3078
John McCall33ddac02011-01-19 10:06:00 +00003079QualType ASTContext::getBaseElementType(QualType type) const {
3080 Qualifiers qs;
3081 while (true) {
3082 SplitQualType split = type.getSplitDesugaredType();
3083 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3084 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003085
John McCall33ddac02011-01-19 10:06:00 +00003086 type = array->getElementType();
3087 qs.addConsistentQualifiers(split.second);
3088 }
Mike Stump11289f42009-09-09 15:08:12 +00003089
John McCall33ddac02011-01-19 10:06:00 +00003090 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003091}
3092
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003093/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003094uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003095ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3096 uint64_t ElementCount = 1;
3097 do {
3098 ElementCount *= CA->getSize().getZExtValue();
3099 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3100 } while (CA);
3101 return ElementCount;
3102}
3103
Steve Naroff0af91202007-04-27 21:51:21 +00003104/// getFloatingRank - Return a relative rank for floating point types.
3105/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003106static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003107 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003108 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003109
John McCall9dd450b2009-09-21 23:43:11 +00003110 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3111 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003112 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003113 case BuiltinType::Float: return FloatRank;
3114 case BuiltinType::Double: return DoubleRank;
3115 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003116 }
3117}
3118
Mike Stump11289f42009-09-09 15:08:12 +00003119/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3120/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003121/// 'typeDomain' is a real floating point or complex type.
3122/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003123QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3124 QualType Domain) const {
3125 FloatingRank EltRank = getFloatingRank(Size);
3126 if (Domain->isComplexType()) {
3127 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003128 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003129 case FloatRank: return FloatComplexTy;
3130 case DoubleRank: return DoubleComplexTy;
3131 case LongDoubleRank: return LongDoubleComplexTy;
3132 }
Steve Naroff0af91202007-04-27 21:51:21 +00003133 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003134
3135 assert(Domain->isRealFloatingType() && "Unknown domain!");
3136 switch (EltRank) {
3137 default: assert(0 && "getFloatingRank(): illegal value for rank");
3138 case FloatRank: return FloatTy;
3139 case DoubleRank: return DoubleTy;
3140 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003141 }
Steve Naroffe4718892007-04-27 18:30:00 +00003142}
3143
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003144/// getFloatingTypeOrder - Compare the rank of the two specified floating
3145/// point types, ignoring the domain of the type (i.e. 'double' ==
3146/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003147/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003148int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003149 FloatingRank LHSR = getFloatingRank(LHS);
3150 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003151
Chris Lattnerb90739d2008-04-06 23:38:49 +00003152 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003153 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003154 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003155 return 1;
3156 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003157}
3158
Chris Lattner76a00cf2008-04-06 22:59:24 +00003159/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3160/// routine will assert if passed a built-in type that isn't an integer or enum,
3161/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003162unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003163 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003164 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003165 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003166
Chris Lattnerad3467e2010-12-25 23:25:43 +00003167 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3168 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003169 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3170
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003171 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3172 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3173
3174 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3175 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3176
Chris Lattner76a00cf2008-04-06 22:59:24 +00003177 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003178 default: assert(0 && "getIntegerRank(): not a built-in integer");
3179 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003180 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003181 case BuiltinType::Char_S:
3182 case BuiltinType::Char_U:
3183 case BuiltinType::SChar:
3184 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003185 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003186 case BuiltinType::Short:
3187 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003188 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003189 case BuiltinType::Int:
3190 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003191 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003192 case BuiltinType::Long:
3193 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003194 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003195 case BuiltinType::LongLong:
3196 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003197 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003198 case BuiltinType::Int128:
3199 case BuiltinType::UInt128:
3200 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003201 }
3202}
3203
Eli Friedman629ffb92009-08-20 04:21:42 +00003204/// \brief Whether this is a promotable bitfield reference according
3205/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3206///
3207/// \returns the type this bit-field will promote to, or NULL if no
3208/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003209QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003210 if (E->isTypeDependent() || E->isValueDependent())
3211 return QualType();
3212
Eli Friedman629ffb92009-08-20 04:21:42 +00003213 FieldDecl *Field = E->getBitField();
3214 if (!Field)
3215 return QualType();
3216
3217 QualType FT = Field->getType();
3218
3219 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3220 uint64_t BitWidth = BitWidthAP.getZExtValue();
3221 uint64_t IntSize = getTypeSize(IntTy);
3222 // GCC extension compatibility: if the bit-field size is less than or equal
3223 // to the size of int, it gets promoted no matter what its type is.
3224 // For instance, unsigned long bf : 4 gets promoted to signed int.
3225 if (BitWidth < IntSize)
3226 return IntTy;
3227
3228 if (BitWidth == IntSize)
3229 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3230
3231 // Types bigger than int are not subject to promotions, and therefore act
3232 // like the base type.
3233 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3234 // is ridiculous.
3235 return QualType();
3236}
3237
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003238/// getPromotedIntegerType - Returns the type that Promotable will
3239/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3240/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003241QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003242 assert(!Promotable.isNull());
3243 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003244 if (const EnumType *ET = Promotable->getAs<EnumType>())
3245 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003246 if (Promotable->isSignedIntegerType())
3247 return IntTy;
3248 uint64_t PromotableSize = getTypeSize(Promotable);
3249 uint64_t IntSize = getTypeSize(IntTy);
3250 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3251 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3252}
3253
Mike Stump11289f42009-09-09 15:08:12 +00003254/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003255/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003256/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003257int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003258 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3259 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003260 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003261
Chris Lattner76a00cf2008-04-06 22:59:24 +00003262 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3263 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003264
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003265 unsigned LHSRank = getIntegerRank(LHSC);
3266 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003267
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003268 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3269 if (LHSRank == RHSRank) return 0;
3270 return LHSRank > RHSRank ? 1 : -1;
3271 }
Mike Stump11289f42009-09-09 15:08:12 +00003272
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003273 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3274 if (LHSUnsigned) {
3275 // If the unsigned [LHS] type is larger, return it.
3276 if (LHSRank >= RHSRank)
3277 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003278
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003279 // If the signed type can represent all values of the unsigned type, it
3280 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003281 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003282 return -1;
3283 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003284
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003285 // If the unsigned [RHS] type is larger, return it.
3286 if (RHSRank >= LHSRank)
3287 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003288
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003289 // If the signed type can represent all values of the unsigned type, it
3290 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003291 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003292 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003293}
Anders Carlsson98f07902007-08-17 05:31:46 +00003294
Anders Carlsson6d417272009-11-14 21:45:58 +00003295static RecordDecl *
Jay Foad39c79802011-01-12 09:06:06 +00003296CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson6d417272009-11-14 21:45:58 +00003297 SourceLocation L, IdentifierInfo *Id) {
3298 if (Ctx.getLangOptions().CPlusPlus)
3299 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3300 else
3301 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3302}
3303
Mike Stump11289f42009-09-09 15:08:12 +00003304// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003305QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003306 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003307 CFConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003308 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003309 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003310 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003311
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003312 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003313
Anders Carlsson98f07902007-08-17 05:31:46 +00003314 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003315 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003316 // int flags;
3317 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003318 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003319 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003320 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003321 FieldTypes[3] = LongTy;
3322
Anders Carlsson98f07902007-08-17 05:31:46 +00003323 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003324 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003325 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00003326 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003327 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003328 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003329 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003330 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003331 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003332 }
3333
Douglas Gregord5058122010-02-11 01:19:42 +00003334 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003335 }
Mike Stump11289f42009-09-09 15:08:12 +00003336
Anders Carlsson98f07902007-08-17 05:31:46 +00003337 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003338}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003339
Douglas Gregor512b0772009-04-23 22:29:11 +00003340void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003341 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003342 assert(Rec && "Invalid CFConstantStringType");
3343 CFConstantStringTypeDecl = Rec->getDecl();
3344}
3345
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003346// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003347QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003348 if (!NSConstantStringTypeDecl) {
3349 NSConstantStringTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003350 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003351 &Idents.get("__builtin_NSString"));
3352 NSConstantStringTypeDecl->startDefinition();
3353
3354 QualType FieldTypes[3];
3355
3356 // const int *isa;
3357 FieldTypes[0] = getPointerType(IntTy.withConst());
3358 // const char *str;
3359 FieldTypes[1] = getPointerType(CharTy.withConst());
3360 // unsigned int length;
3361 FieldTypes[2] = UnsignedIntTy;
3362
3363 // Create fields
3364 for (unsigned i = 0; i < 3; ++i) {
3365 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3366 SourceLocation(), 0,
3367 FieldTypes[i], /*TInfo=*/0,
3368 /*BitWidth=*/0,
3369 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003370 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003371 NSConstantStringTypeDecl->addDecl(Field);
3372 }
3373
3374 NSConstantStringTypeDecl->completeDefinition();
3375 }
3376
3377 return getTagDeclType(NSConstantStringTypeDecl);
3378}
3379
3380void ASTContext::setNSConstantStringType(QualType T) {
3381 const RecordType *Rec = T->getAs<RecordType>();
3382 assert(Rec && "Invalid NSConstantStringType");
3383 NSConstantStringTypeDecl = Rec->getDecl();
3384}
3385
Jay Foad39c79802011-01-12 09:06:06 +00003386QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003387 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003388 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara6150c882010-05-11 21:36:43 +00003389 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003390 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003391 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003392
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003393 QualType FieldTypes[] = {
3394 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003395 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003396 getPointerType(UnsignedLongTy),
3397 getConstantArrayType(UnsignedLongTy,
3398 llvm::APInt(32, 5), ArrayType::Normal, 0)
3399 };
Mike Stump11289f42009-09-09 15:08:12 +00003400
Douglas Gregor91f84212008-12-11 16:49:14 +00003401 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003402 FieldDecl *Field = FieldDecl::Create(*this,
3403 ObjCFastEnumerationStateTypeDecl,
3404 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003405 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003406 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003407 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003408 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003409 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003410 }
Mike Stump11289f42009-09-09 15:08:12 +00003411
Douglas Gregord5058122010-02-11 01:19:42 +00003412 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003413 }
Mike Stump11289f42009-09-09 15:08:12 +00003414
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003415 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3416}
3417
Jay Foad39c79802011-01-12 09:06:06 +00003418QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003419 if (BlockDescriptorType)
3420 return getTagDeclType(BlockDescriptorType);
3421
3422 RecordDecl *T;
3423 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003424 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003425 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003426 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003427
3428 QualType FieldTypes[] = {
3429 UnsignedLongTy,
3430 UnsignedLongTy,
3431 };
3432
3433 const char *FieldNames[] = {
3434 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003435 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003436 };
3437
3438 for (size_t i = 0; i < 2; ++i) {
3439 FieldDecl *Field = FieldDecl::Create(*this,
3440 T,
3441 SourceLocation(),
3442 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003443 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003444 /*BitWidth=*/0,
3445 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003446 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003447 T->addDecl(Field);
3448 }
3449
Douglas Gregord5058122010-02-11 01:19:42 +00003450 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003451
3452 BlockDescriptorType = T;
3453
3454 return getTagDeclType(BlockDescriptorType);
3455}
3456
3457void ASTContext::setBlockDescriptorType(QualType T) {
3458 const RecordType *Rec = T->getAs<RecordType>();
3459 assert(Rec && "Invalid BlockDescriptorType");
3460 BlockDescriptorType = Rec->getDecl();
3461}
3462
Jay Foad39c79802011-01-12 09:06:06 +00003463QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003464 if (BlockDescriptorExtendedType)
3465 return getTagDeclType(BlockDescriptorExtendedType);
3466
3467 RecordDecl *T;
3468 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003469 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003470 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003471 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003472
3473 QualType FieldTypes[] = {
3474 UnsignedLongTy,
3475 UnsignedLongTy,
3476 getPointerType(VoidPtrTy),
3477 getPointerType(VoidPtrTy)
3478 };
3479
3480 const char *FieldNames[] = {
3481 "reserved",
3482 "Size",
3483 "CopyFuncPtr",
3484 "DestroyFuncPtr"
3485 };
3486
3487 for (size_t i = 0; i < 4; ++i) {
3488 FieldDecl *Field = FieldDecl::Create(*this,
3489 T,
3490 SourceLocation(),
3491 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003492 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003493 /*BitWidth=*/0,
3494 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003495 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003496 T->addDecl(Field);
3497 }
3498
Douglas Gregord5058122010-02-11 01:19:42 +00003499 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003500
3501 BlockDescriptorExtendedType = T;
3502
3503 return getTagDeclType(BlockDescriptorExtendedType);
3504}
3505
3506void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3507 const RecordType *Rec = T->getAs<RecordType>();
3508 assert(Rec && "Invalid BlockDescriptorType");
3509 BlockDescriptorExtendedType = Rec->getDecl();
3510}
3511
Jay Foad39c79802011-01-12 09:06:06 +00003512bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003513 if (Ty->isBlockPointerType())
3514 return true;
3515 if (isObjCNSObjectType(Ty))
3516 return true;
3517 if (Ty->isObjCObjectPointerType())
3518 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003519 if (getLangOptions().CPlusPlus) {
3520 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3521 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3522 return RD->hasConstCopyConstructor(*this);
3523
3524 }
3525 }
Mike Stump94967902009-10-21 18:16:27 +00003526 return false;
3527}
3528
Jay Foad39c79802011-01-12 09:06:06 +00003529QualType
3530ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003531 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003532 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003533 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003534 // unsigned int __flags;
3535 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003536 // void *__copy_helper; // as needed
3537 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003538 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003539 // } *
3540
Mike Stump94967902009-10-21 18:16:27 +00003541 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3542
3543 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003544 llvm::SmallString<36> Name;
3545 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3546 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003547 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003548 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003549 &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003550 T->startDefinition();
3551 QualType Int32Ty = IntTy;
3552 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3553 QualType FieldTypes[] = {
3554 getPointerType(VoidPtrTy),
3555 getPointerType(getTagDeclType(T)),
3556 Int32Ty,
3557 Int32Ty,
3558 getPointerType(VoidPtrTy),
3559 getPointerType(VoidPtrTy),
3560 Ty
3561 };
3562
Daniel Dunbar56df9772010-08-17 22:39:59 +00003563 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003564 "__isa",
3565 "__forwarding",
3566 "__flags",
3567 "__size",
3568 "__copy_helper",
3569 "__destroy_helper",
3570 DeclName,
3571 };
3572
3573 for (size_t i = 0; i < 7; ++i) {
3574 if (!HasCopyAndDispose && i >=4 && i <= 5)
3575 continue;
3576 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3577 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003578 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003579 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003580 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003581 T->addDecl(Field);
3582 }
3583
Douglas Gregord5058122010-02-11 01:19:42 +00003584 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003585
3586 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003587}
3588
3589
3590QualType ASTContext::getBlockParmType(
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003591 bool BlockHasCopyDispose,
Jay Foad39c79802011-01-12 09:06:06 +00003592 llvm::SmallVectorImpl<const Expr *> &Layout) const {
John McCall87fe5d52010-05-20 01:18:31 +00003593
Mike Stumpd0153282009-10-20 02:12:22 +00003594 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003595 llvm::SmallString<36> Name;
3596 llvm::raw_svector_ostream(Name) << "__block_literal_"
3597 << ++UniqueBlockParmTypeID;
Mike Stumpd0153282009-10-20 02:12:22 +00003598 RecordDecl *T;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003599 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson6d417272009-11-14 21:45:58 +00003600 &Idents.get(Name.str()));
John McCallae580fe2010-02-05 01:33:36 +00003601 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003602 QualType FieldTypes[] = {
3603 getPointerType(VoidPtrTy),
3604 IntTy,
3605 IntTy,
3606 getPointerType(VoidPtrTy),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003607 (BlockHasCopyDispose ?
3608 getPointerType(getBlockDescriptorExtendedType()) :
3609 getPointerType(getBlockDescriptorType()))
Mike Stumpd0153282009-10-20 02:12:22 +00003610 };
3611
3612 const char *FieldNames[] = {
3613 "__isa",
3614 "__flags",
3615 "__reserved",
3616 "__FuncPtr",
3617 "__descriptor"
3618 };
3619
3620 for (size_t i = 0; i < 5; ++i) {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003621 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003622 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003623 FieldTypes[i], /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003624 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003625 Field->setAccess(AS_public);
Mike Stump7fe9cc12009-10-21 03:49:08 +00003626 T->addDecl(Field);
3627 }
3628
John McCall87fe5d52010-05-20 01:18:31 +00003629 for (unsigned i = 0; i < Layout.size(); ++i) {
3630 const Expr *E = Layout[i];
Mike Stump7fe9cc12009-10-21 03:49:08 +00003631
John McCall87fe5d52010-05-20 01:18:31 +00003632 QualType FieldType = E->getType();
3633 IdentifierInfo *FieldName = 0;
3634 if (isa<CXXThisExpr>(E)) {
3635 FieldName = &Idents.get("this");
3636 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3637 const ValueDecl *D = BDRE->getDecl();
3638 FieldName = D->getIdentifier();
3639 if (BDRE->isByRef())
Daniel Dunbar56df9772010-08-17 22:39:59 +00003640 FieldType = BuildByRefType(D->getName(), FieldType);
John McCall87fe5d52010-05-20 01:18:31 +00003641 } else {
3642 // Padding.
3643 assert(isa<ConstantArrayType>(FieldType) &&
3644 isa<DeclRefExpr>(E) &&
3645 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3646 "doesn't match characteristics of padding decl");
3647 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00003648
3649 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCall87fe5d52010-05-20 01:18:31 +00003650 FieldName, FieldType, /*TInfo=*/0,
Mike Stump7fe9cc12009-10-21 03:49:08 +00003651 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003652 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003653 T->addDecl(Field);
3654 }
3655
Douglas Gregord5058122010-02-11 01:19:42 +00003656 T->completeDefinition();
Mike Stump7fe9cc12009-10-21 03:49:08 +00003657
3658 return getPointerType(getTagDeclType(T));
Mike Stumpd0153282009-10-20 02:12:22 +00003659}
3660
Douglas Gregor512b0772009-04-23 22:29:11 +00003661void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003662 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003663 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3664 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3665}
3666
Anders Carlsson18acd442007-10-29 06:33:42 +00003667// This returns true if a type has been typedefed to BOOL:
3668// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003669static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003670 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003671 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3672 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003673
Anders Carlssond8499822007-10-29 05:01:08 +00003674 return false;
3675}
3676
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003677/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003678/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003679CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003680 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003681
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003682 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003683 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003684 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003685 // Treat arrays as pointers, since that's how they're passed in.
3686 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003687 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003688 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003689}
3690
3691static inline
3692std::string charUnitsToString(const CharUnits &CU) {
3693 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003694}
3695
John McCall351762c2011-02-07 10:33:21 +00003696/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003697/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003698std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3699 std::string S;
3700
David Chisnall950a9512009-11-17 19:33:30 +00003701 const BlockDecl *Decl = Expr->getBlockDecl();
3702 QualType BlockTy =
3703 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3704 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003705 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003706 // Compute size of all parameters.
3707 // Start with computing size of a pointer in number of bytes.
3708 // FIXME: There might(should) be a better way of doing this computation!
3709 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003710 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3711 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003712 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003713 E = Decl->param_end(); PI != E; ++PI) {
3714 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003715 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003716 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003717 ParmOffset += sz;
3718 }
3719 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003720 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003721 // Block pointer and offset.
3722 S += "@?0";
3723 ParmOffset = PtrSize;
3724
3725 // Argument types.
3726 ParmOffset = PtrSize;
3727 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3728 Decl->param_end(); PI != E; ++PI) {
3729 ParmVarDecl *PVDecl = *PI;
3730 QualType PType = PVDecl->getOriginalType();
3731 if (const ArrayType *AT =
3732 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3733 // Use array's original type only if it has known number of
3734 // elements.
3735 if (!isa<ConstantArrayType>(AT))
3736 PType = PVDecl->getType();
3737 } else if (PType->isFunctionType())
3738 PType = PVDecl->getType();
3739 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003740 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003741 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003742 }
John McCall351762c2011-02-07 10:33:21 +00003743
3744 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003745}
3746
David Chisnall50e4eba2010-12-30 14:05:53 +00003747void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3748 std::string& S) {
3749 // Encode result type.
3750 getObjCEncodingForType(Decl->getResultType(), S);
3751 CharUnits ParmOffset;
3752 // Compute size of all parameters.
3753 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3754 E = Decl->param_end(); PI != E; ++PI) {
3755 QualType PType = (*PI)->getType();
3756 CharUnits sz = getObjCEncodingTypeSize(PType);
3757 assert (sz.isPositive() &&
3758 "getObjCEncodingForMethodDecl - Incomplete param type");
3759 ParmOffset += sz;
3760 }
3761 S += charUnitsToString(ParmOffset);
3762 ParmOffset = CharUnits::Zero();
3763
3764 // Argument types.
3765 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3766 E = Decl->param_end(); PI != E; ++PI) {
3767 ParmVarDecl *PVDecl = *PI;
3768 QualType PType = PVDecl->getOriginalType();
3769 if (const ArrayType *AT =
3770 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3771 // Use array's original type only if it has known number of
3772 // elements.
3773 if (!isa<ConstantArrayType>(AT))
3774 PType = PVDecl->getType();
3775 } else if (PType->isFunctionType())
3776 PType = PVDecl->getType();
3777 getObjCEncodingForType(PType, S);
3778 S += charUnitsToString(ParmOffset);
3779 ParmOffset += getObjCEncodingTypeSize(PType);
3780 }
3781}
3782
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003783/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003784/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003785void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003786 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003787 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003788 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003789 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003790 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003791 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003792 // Compute size of all parameters.
3793 // Start with computing size of a pointer in number of bytes.
3794 // FIXME: There might(should) be a better way of doing this computation!
3795 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003796 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003797 // The first two arguments (self and _cmd) are pointers; account for
3798 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003799 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003800 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003801 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003802 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003803 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003804 assert (sz.isPositive() &&
3805 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003806 ParmOffset += sz;
3807 }
Ken Dyck40775002010-01-11 17:06:35 +00003808 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003809 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003810 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003811
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003812 // Argument types.
3813 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003814 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003815 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003816 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003817 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003818 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003819 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3820 // Use array's original type only if it has known number of
3821 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003822 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003823 PType = PVDecl->getType();
3824 } else if (PType->isFunctionType())
3825 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003826 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003827 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003828 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003829 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003830 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003831 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003832 }
3833}
3834
Daniel Dunbar4932b362008-08-28 04:38:10 +00003835/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003836/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003837/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3838/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003839/// Property attributes are stored as a comma-delimited C string. The simple
3840/// attributes readonly and bycopy are encoded as single characters. The
3841/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3842/// encoded as single characters, followed by an identifier. Property types
3843/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003844/// these attributes are defined by the following enumeration:
3845/// @code
3846/// enum PropertyAttributes {
3847/// kPropertyReadOnly = 'R', // property is read-only.
3848/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3849/// kPropertyByref = '&', // property is a reference to the value last assigned
3850/// kPropertyDynamic = 'D', // property is dynamic
3851/// kPropertyGetter = 'G', // followed by getter selector name
3852/// kPropertySetter = 'S', // followed by setter selector name
3853/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3854/// kPropertyType = 't' // followed by old-style type encoding.
3855/// kPropertyWeak = 'W' // 'weak' property
3856/// kPropertyStrong = 'P' // property GC'able
3857/// kPropertyNonAtomic = 'N' // property non-atomic
3858/// };
3859/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003860void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003861 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003862 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003863 // Collect information from the property implementation decl(s).
3864 bool Dynamic = false;
3865 ObjCPropertyImplDecl *SynthesizePID = 0;
3866
3867 // FIXME: Duplicated code due to poor abstraction.
3868 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003869 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003870 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3871 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003872 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003873 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003874 ObjCPropertyImplDecl *PID = *i;
3875 if (PID->getPropertyDecl() == PD) {
3876 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3877 Dynamic = true;
3878 } else {
3879 SynthesizePID = PID;
3880 }
3881 }
3882 }
3883 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003884 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003885 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003886 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003887 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003888 ObjCPropertyImplDecl *PID = *i;
3889 if (PID->getPropertyDecl() == PD) {
3890 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3891 Dynamic = true;
3892 } else {
3893 SynthesizePID = PID;
3894 }
3895 }
Mike Stump11289f42009-09-09 15:08:12 +00003896 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003897 }
3898 }
3899
3900 // FIXME: This is not very efficient.
3901 S = "T";
3902
3903 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003904 // GCC has some special rules regarding encoding of properties which
3905 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003906 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003907 true /* outermost type */,
3908 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003909
3910 if (PD->isReadOnly()) {
3911 S += ",R";
3912 } else {
3913 switch (PD->getSetterKind()) {
3914 case ObjCPropertyDecl::Assign: break;
3915 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003916 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003917 }
3918 }
3919
3920 // It really isn't clear at all what this means, since properties
3921 // are "dynamic by default".
3922 if (Dynamic)
3923 S += ",D";
3924
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003925 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3926 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003927
Daniel Dunbar4932b362008-08-28 04:38:10 +00003928 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3929 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003930 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003931 }
3932
3933 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3934 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003935 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003936 }
3937
3938 if (SynthesizePID) {
3939 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3940 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003941 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003942 }
3943
3944 // FIXME: OBJCGC: weak & strong
3945}
3946
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003947/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003948/// Another legacy compatibility encoding: 32-bit longs are encoded as
3949/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003950/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3951///
3952void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003953 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003954 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003955 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003956 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003957 else
Jay Foad39c79802011-01-12 09:06:06 +00003958 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003959 PointeeTy = IntTy;
3960 }
3961 }
3962}
3963
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003964void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003965 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003966 // We follow the behavior of gcc, expanding structures which are
3967 // directly pointed to, and expanding embedded structures. Note that
3968 // these rules are sufficient to prevent recursive encoding of the
3969 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003970 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003971 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003972}
3973
David Chisnallb190a2c2010-06-04 01:10:52 +00003974static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3975 switch (T->getAs<BuiltinType>()->getKind()) {
3976 default: assert(0 && "Unhandled builtin type kind");
3977 case BuiltinType::Void: return 'v';
3978 case BuiltinType::Bool: return 'B';
3979 case BuiltinType::Char_U:
3980 case BuiltinType::UChar: return 'C';
3981 case BuiltinType::UShort: return 'S';
3982 case BuiltinType::UInt: return 'I';
3983 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00003984 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003985 case BuiltinType::UInt128: return 'T';
3986 case BuiltinType::ULongLong: return 'Q';
3987 case BuiltinType::Char_S:
3988 case BuiltinType::SChar: return 'c';
3989 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00003990 case BuiltinType::WChar_S:
3991 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00003992 case BuiltinType::Int: return 'i';
3993 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00003994 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00003995 case BuiltinType::LongLong: return 'q';
3996 case BuiltinType::Int128: return 't';
3997 case BuiltinType::Float: return 'f';
3998 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00003999 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004000 }
4001}
4002
Jay Foad39c79802011-01-12 09:06:06 +00004003static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004004 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004005 const Expr *E = FD->getBitWidth();
4006 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004007 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004008 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4009 // The GNU runtime requires more information; bitfields are encoded as b,
4010 // then the offset (in bits) of the first element, then the type of the
4011 // bitfield, then the size in bits. For example, in this structure:
4012 //
4013 // struct
4014 // {
4015 // int integer;
4016 // int flags:2;
4017 // };
4018 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4019 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4020 // information is not especially sensible, but we're stuck with it for
4021 // compatibility with GCC, although providing it breaks anything that
4022 // actually uses runtime introspection and wants to work on both runtimes...
4023 if (!Ctx->getLangOptions().NeXTRuntime) {
4024 const RecordDecl *RD = FD->getParent();
4025 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4026 // FIXME: This same linear search is also used in ExprConstant - it might
4027 // be better if the FieldDecl stored its offset. We'd be increasing the
4028 // size of the object slightly, but saving some time every time it is used.
4029 unsigned i = 0;
4030 for (RecordDecl::field_iterator Field = RD->field_begin(),
4031 FieldEnd = RD->field_end();
4032 Field != FieldEnd; (void)++Field, ++i) {
4033 if (*Field == FD)
4034 break;
4035 }
4036 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004037 if (T->isEnumeralType())
4038 S += 'i';
4039 else
Jay Foad39c79802011-01-12 09:06:06 +00004040 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004041 }
4042 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004043 S += llvm::utostr(N);
4044}
4045
Daniel Dunbar07d07852009-10-18 21:17:35 +00004046// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004047void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4048 bool ExpandPointedToStructures,
4049 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004050 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004051 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004052 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004053 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004054 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004055 return EncodeBitField(this, S, T, FD);
4056 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004057 return;
4058 }
Mike Stump11289f42009-09-09 15:08:12 +00004059
John McCall9dd450b2009-09-21 23:43:11 +00004060 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004061 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004062 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004063 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004064 return;
4065 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004066
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004067 // encoding for pointer or r3eference types.
4068 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004069 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004070 if (PT->isObjCSelType()) {
4071 S += ':';
4072 return;
4073 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004074 PointeeTy = PT->getPointeeType();
4075 }
4076 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4077 PointeeTy = RT->getPointeeType();
4078 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004079 bool isReadOnly = false;
4080 // For historical/compatibility reasons, the read-only qualifier of the
4081 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4082 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004083 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004084 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004085 if (OutermostType && T.isConstQualified()) {
4086 isReadOnly = true;
4087 S += 'r';
4088 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004089 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004090 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004091 while (P->getAs<PointerType>())
4092 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004093 if (P.isConstQualified()) {
4094 isReadOnly = true;
4095 S += 'r';
4096 }
4097 }
4098 if (isReadOnly) {
4099 // Another legacy compatibility encoding. Some ObjC qualifier and type
4100 // combinations need to be rearranged.
4101 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004102 if (llvm::StringRef(S).endswith("nr"))
4103 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004104 }
Mike Stump11289f42009-09-09 15:08:12 +00004105
Anders Carlssond8499822007-10-29 05:01:08 +00004106 if (PointeeTy->isCharType()) {
4107 // char pointer types should be encoded as '*' unless it is a
4108 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004109 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004110 S += '*';
4111 return;
4112 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004113 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004114 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4115 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4116 S += '#';
4117 return;
4118 }
4119 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4120 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4121 S += '@';
4122 return;
4123 }
4124 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004125 }
Anders Carlssond8499822007-10-29 05:01:08 +00004126 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004127 getLegacyIntegralTypeEncoding(PointeeTy);
4128
Mike Stump11289f42009-09-09 15:08:12 +00004129 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004130 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004131 return;
4132 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004133
Chris Lattnere7cabb92009-07-13 00:10:46 +00004134 if (const ArrayType *AT =
4135 // Ignore type qualifiers etc.
4136 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004137 if (isa<IncompleteArrayType>(AT)) {
4138 // Incomplete arrays are encoded as a pointer to the array element.
4139 S += '^';
4140
Mike Stump11289f42009-09-09 15:08:12 +00004141 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004142 false, ExpandStructures, FD);
4143 } else {
4144 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004145
Anders Carlssond05f44b2009-02-22 01:38:57 +00004146 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4147 S += llvm::utostr(CAT->getSize().getZExtValue());
4148 else {
4149 //Variable length arrays are encoded as a regular array with 0 elements.
4150 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4151 S += '0';
4152 }
Mike Stump11289f42009-09-09 15:08:12 +00004153
4154 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004155 false, ExpandStructures, FD);
4156 S += ']';
4157 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004158 return;
4159 }
Mike Stump11289f42009-09-09 15:08:12 +00004160
John McCall9dd450b2009-09-21 23:43:11 +00004161 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004162 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004163 return;
4164 }
Mike Stump11289f42009-09-09 15:08:12 +00004165
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004166 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004167 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004168 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004169 // Anonymous structures print as '?'
4170 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4171 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004172 if (ClassTemplateSpecializationDecl *Spec
4173 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4174 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4175 std::string TemplateArgsStr
4176 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004177 TemplateArgs.data(),
4178 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004179 (*this).PrintingPolicy);
4180
4181 S += TemplateArgsStr;
4182 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004183 } else {
4184 S += '?';
4185 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004186 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004187 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004188 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4189 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004190 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004191 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004192 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004193 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004194 S += '"';
4195 }
Mike Stump11289f42009-09-09 15:08:12 +00004196
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004197 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004198 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004199 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004200 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004201 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004202 QualType qt = Field->getType();
4203 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004204 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004205 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004206 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004207 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004208 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004209 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004210 return;
4211 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004212
Chris Lattnere7cabb92009-07-13 00:10:46 +00004213 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004214 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004215 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004216 else
4217 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004218 return;
4219 }
Mike Stump11289f42009-09-09 15:08:12 +00004220
Chris Lattnere7cabb92009-07-13 00:10:46 +00004221 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004222 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004223 return;
4224 }
Mike Stump11289f42009-09-09 15:08:12 +00004225
John McCall8b07ec22010-05-15 11:32:37 +00004226 // Ignore protocol qualifiers when mangling at this level.
4227 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4228 T = OT->getBaseType();
4229
John McCall8ccfcb52009-09-24 19:53:00 +00004230 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004231 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004232 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004233 S += '{';
4234 const IdentifierInfo *II = OI->getIdentifier();
4235 S += II->getName();
4236 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004237 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4238 DeepCollectObjCIvars(OI, true, Ivars);
4239 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4240 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4241 if (Field->isBitField())
4242 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004243 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004244 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004245 }
4246 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004247 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004248 }
Mike Stump11289f42009-09-09 15:08:12 +00004249
John McCall9dd450b2009-09-21 23:43:11 +00004250 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004251 if (OPT->isObjCIdType()) {
4252 S += '@';
4253 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004254 }
Mike Stump11289f42009-09-09 15:08:12 +00004255
Steve Narofff0c86112009-10-28 22:03:49 +00004256 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4257 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4258 // Since this is a binary compatibility issue, need to consult with runtime
4259 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004260 S += '#';
4261 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004262 }
Mike Stump11289f42009-09-09 15:08:12 +00004263
Chris Lattnere7cabb92009-07-13 00:10:46 +00004264 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004265 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004266 ExpandPointedToStructures,
4267 ExpandStructures, FD);
4268 if (FD || EncodingProperty) {
4269 // Note that we do extended encoding of protocol qualifer list
4270 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004271 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004272 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4273 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004274 S += '<';
4275 S += (*I)->getNameAsString();
4276 S += '>';
4277 }
4278 S += '"';
4279 }
4280 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004281 }
Mike Stump11289f42009-09-09 15:08:12 +00004282
Chris Lattnere7cabb92009-07-13 00:10:46 +00004283 QualType PointeeTy = OPT->getPointeeType();
4284 if (!EncodingProperty &&
4285 isa<TypedefType>(PointeeTy.getTypePtr())) {
4286 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004287 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004288 // {...};
4289 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004290 getObjCEncodingForTypeImpl(PointeeTy, S,
4291 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004292 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004293 return;
4294 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004295
4296 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004297 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004298 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004299 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004300 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4301 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004302 S += '<';
4303 S += (*I)->getNameAsString();
4304 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004305 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004306 S += '"';
4307 }
4308 return;
4309 }
Mike Stump11289f42009-09-09 15:08:12 +00004310
John McCalla9e6e8d2010-05-17 23:56:34 +00004311 // gcc just blithely ignores member pointers.
4312 // TODO: maybe there should be a mangling for these
4313 if (T->getAs<MemberPointerType>())
4314 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004315
4316 if (T->isVectorType()) {
4317 // This matches gcc's encoding, even though technically it is
4318 // insufficient.
4319 // FIXME. We should do a better job than gcc.
4320 return;
4321 }
4322
Chris Lattnere7cabb92009-07-13 00:10:46 +00004323 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004324}
4325
Mike Stump11289f42009-09-09 15:08:12 +00004326void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004327 std::string& S) const {
4328 if (QT & Decl::OBJC_TQ_In)
4329 S += 'n';
4330 if (QT & Decl::OBJC_TQ_Inout)
4331 S += 'N';
4332 if (QT & Decl::OBJC_TQ_Out)
4333 S += 'o';
4334 if (QT & Decl::OBJC_TQ_Bycopy)
4335 S += 'O';
4336 if (QT & Decl::OBJC_TQ_Byref)
4337 S += 'R';
4338 if (QT & Decl::OBJC_TQ_Oneway)
4339 S += 'V';
4340}
4341
Chris Lattnere7cabb92009-07-13 00:10:46 +00004342void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004343 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004344
Anders Carlsson87c149b2007-10-11 01:00:40 +00004345 BuiltinVaListType = T;
4346}
4347
Chris Lattnere7cabb92009-07-13 00:10:46 +00004348void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004349 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004350}
4351
Chris Lattnere7cabb92009-07-13 00:10:46 +00004352void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004353 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004354}
4355
Chris Lattnere7cabb92009-07-13 00:10:46 +00004356void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004357 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004358}
4359
Chris Lattnere7cabb92009-07-13 00:10:46 +00004360void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004361 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004362}
4363
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004364void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004365 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004366 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004367
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004368 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004369}
4370
John McCalld28ae272009-12-02 08:04:21 +00004371/// \brief Retrieve the template name that corresponds to a non-empty
4372/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004373TemplateName
4374ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4375 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004376 unsigned size = End - Begin;
4377 assert(size > 1 && "set is not overloaded!");
4378
4379 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4380 size * sizeof(FunctionTemplateDecl*));
4381 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4382
4383 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004384 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004385 NamedDecl *D = *I;
4386 assert(isa<FunctionTemplateDecl>(D) ||
4387 (isa<UsingShadowDecl>(D) &&
4388 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4389 *Storage++ = D;
4390 }
4391
4392 return TemplateName(OT);
4393}
4394
Douglas Gregordc572a32009-03-30 22:58:21 +00004395/// \brief Retrieve the template name that represents a qualified
4396/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004397TemplateName
4398ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4399 bool TemplateKeyword,
4400 TemplateDecl *Template) const {
Douglas Gregorc42075a2010-02-04 18:10:26 +00004401 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004402 llvm::FoldingSetNodeID ID;
4403 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4404
4405 void *InsertPos = 0;
4406 QualifiedTemplateName *QTN =
4407 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4408 if (!QTN) {
4409 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4410 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4411 }
4412
4413 return TemplateName(QTN);
4414}
4415
4416/// \brief Retrieve the template name that represents a dependent
4417/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004418TemplateName
4419ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4420 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004421 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004422 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004423
4424 llvm::FoldingSetNodeID ID;
4425 DependentTemplateName::Profile(ID, NNS, Name);
4426
4427 void *InsertPos = 0;
4428 DependentTemplateName *QTN =
4429 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4430
4431 if (QTN)
4432 return TemplateName(QTN);
4433
4434 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4435 if (CanonNNS == NNS) {
4436 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4437 } else {
4438 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4439 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004440 DependentTemplateName *CheckQTN =
4441 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4442 assert(!CheckQTN && "Dependent type name canonicalization broken");
4443 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004444 }
4445
4446 DependentTemplateNames.InsertNode(QTN, InsertPos);
4447 return TemplateName(QTN);
4448}
4449
Douglas Gregor71395fa2009-11-04 00:56:37 +00004450/// \brief Retrieve the template name that represents a dependent
4451/// template name such as \c MetaFun::template operator+.
4452TemplateName
4453ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004454 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004455 assert((!NNS || NNS->isDependent()) &&
4456 "Nested name specifier must be dependent");
4457
4458 llvm::FoldingSetNodeID ID;
4459 DependentTemplateName::Profile(ID, NNS, Operator);
4460
4461 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004462 DependentTemplateName *QTN
4463 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004464
4465 if (QTN)
4466 return TemplateName(QTN);
4467
4468 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4469 if (CanonNNS == NNS) {
4470 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4471 } else {
4472 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4473 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004474
4475 DependentTemplateName *CheckQTN
4476 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4477 assert(!CheckQTN && "Dependent template name canonicalization broken");
4478 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004479 }
4480
4481 DependentTemplateNames.InsertNode(QTN, InsertPos);
4482 return TemplateName(QTN);
4483}
4484
Douglas Gregor5590be02011-01-15 06:45:20 +00004485TemplateName
4486ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4487 const TemplateArgument &ArgPack) const {
4488 ASTContext &Self = const_cast<ASTContext &>(*this);
4489 llvm::FoldingSetNodeID ID;
4490 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4491
4492 void *InsertPos = 0;
4493 SubstTemplateTemplateParmPackStorage *Subst
4494 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4495
4496 if (!Subst) {
4497 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4498 ArgPack.pack_size(),
4499 ArgPack.pack_begin());
4500 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4501 }
4502
4503 return TemplateName(Subst);
4504}
4505
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004506/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004507/// TargetInfo, produce the corresponding type. The unsigned @p Type
4508/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004509CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004510 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004511 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004512 case TargetInfo::SignedShort: return ShortTy;
4513 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4514 case TargetInfo::SignedInt: return IntTy;
4515 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4516 case TargetInfo::SignedLong: return LongTy;
4517 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4518 case TargetInfo::SignedLongLong: return LongLongTy;
4519 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4520 }
4521
4522 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004523 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004524}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004525
4526//===----------------------------------------------------------------------===//
4527// Type Predicates.
4528//===----------------------------------------------------------------------===//
4529
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004530/// isObjCNSObjectType - Return true if this is an NSObject object using
4531/// NSObject attribute on a c-style pointer type.
4532/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004533/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004534///
4535bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCall424cec92011-01-19 06:33:43 +00004536 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004537 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004538 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004539 return true;
4540 }
Mike Stump11289f42009-09-09 15:08:12 +00004541 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004542}
4543
Fariborz Jahanian96207692009-02-18 21:49:28 +00004544/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4545/// garbage collection attribute.
4546///
John McCall553d45a2011-01-12 00:34:59 +00004547Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4548 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4549 return Qualifiers::GCNone;
4550
4551 assert(getLangOptions().ObjC1);
4552 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4553
4554 // Default behaviour under objective-C's gc is for ObjC pointers
4555 // (or pointers to them) be treated as though they were declared
4556 // as __strong.
4557 if (GCAttrs == Qualifiers::GCNone) {
4558 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4559 return Qualifiers::Strong;
4560 else if (Ty->isPointerType())
4561 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4562 } else {
4563 // It's not valid to set GC attributes on anything that isn't a
4564 // pointer.
4565#ifndef NDEBUG
4566 QualType CT = Ty->getCanonicalTypeInternal();
4567 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4568 CT = AT->getElementType();
4569 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4570#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004571 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004572 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004573}
4574
Chris Lattner49af6a42008-04-07 06:51:04 +00004575//===----------------------------------------------------------------------===//
4576// Type Compatibility Testing
4577//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004578
Mike Stump11289f42009-09-09 15:08:12 +00004579/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004580/// compatible.
4581static bool areCompatVectorTypes(const VectorType *LHS,
4582 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004583 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004584 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004585 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004586}
4587
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004588bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4589 QualType SecondVec) {
4590 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4591 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4592
4593 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4594 return true;
4595
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004596 // Treat Neon vector types and most AltiVec vector types as if they are the
4597 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004598 const VectorType *First = FirstVec->getAs<VectorType>();
4599 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004600 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004601 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004602 First->getVectorKind() != VectorType::AltiVecPixel &&
4603 First->getVectorKind() != VectorType::AltiVecBool &&
4604 Second->getVectorKind() != VectorType::AltiVecPixel &&
4605 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004606 return true;
4607
4608 return false;
4609}
4610
Steve Naroff8e6aee52009-07-23 01:01:38 +00004611//===----------------------------------------------------------------------===//
4612// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4613//===----------------------------------------------------------------------===//
4614
4615/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4616/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004617bool
4618ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4619 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004620 if (lProto == rProto)
4621 return true;
4622 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4623 E = rProto->protocol_end(); PI != E; ++PI)
4624 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4625 return true;
4626 return false;
4627}
4628
Steve Naroff8e6aee52009-07-23 01:01:38 +00004629/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4630/// return true if lhs's protocols conform to rhs's protocol; false
4631/// otherwise.
4632bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4633 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4634 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4635 return false;
4636}
4637
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004638/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4639/// Class<p1, ...>.
4640bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4641 QualType rhs) {
4642 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4643 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4644 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4645
4646 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4647 E = lhsQID->qual_end(); I != E; ++I) {
4648 bool match = false;
4649 ObjCProtocolDecl *lhsProto = *I;
4650 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4651 E = rhsOPT->qual_end(); J != E; ++J) {
4652 ObjCProtocolDecl *rhsProto = *J;
4653 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4654 match = true;
4655 break;
4656 }
4657 }
4658 if (!match)
4659 return false;
4660 }
4661 return true;
4662}
4663
Steve Naroff8e6aee52009-07-23 01:01:38 +00004664/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4665/// ObjCQualifiedIDType.
4666bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4667 bool compare) {
4668 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004669 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004670 lhs->isObjCIdType() || lhs->isObjCClassType())
4671 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004672 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004673 rhs->isObjCIdType() || rhs->isObjCClassType())
4674 return true;
4675
4676 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004677 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004678
Steve Naroff8e6aee52009-07-23 01:01:38 +00004679 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004680
Steve Naroff8e6aee52009-07-23 01:01:38 +00004681 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004682 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004683 // make sure we check the class hierarchy.
4684 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4685 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4686 E = lhsQID->qual_end(); I != E; ++I) {
4687 // when comparing an id<P> on lhs with a static type on rhs,
4688 // see if static class implements all of id's protocols, directly or
4689 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004690 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004691 return false;
4692 }
4693 }
4694 // If there are no qualifiers and no interface, we have an 'id'.
4695 return true;
4696 }
Mike Stump11289f42009-09-09 15:08:12 +00004697 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004698 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4699 E = lhsQID->qual_end(); I != E; ++I) {
4700 ObjCProtocolDecl *lhsProto = *I;
4701 bool match = false;
4702
4703 // when comparing an id<P> on lhs with a static type on rhs,
4704 // see if static class implements all of id's protocols, directly or
4705 // through its super class and categories.
4706 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4707 E = rhsOPT->qual_end(); J != E; ++J) {
4708 ObjCProtocolDecl *rhsProto = *J;
4709 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4710 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4711 match = true;
4712 break;
4713 }
4714 }
Mike Stump11289f42009-09-09 15:08:12 +00004715 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004716 // make sure we check the class hierarchy.
4717 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4718 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4719 E = lhsQID->qual_end(); I != E; ++I) {
4720 // when comparing an id<P> on lhs with a static type on rhs,
4721 // see if static class implements all of id's protocols, directly or
4722 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004723 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004724 match = true;
4725 break;
4726 }
4727 }
4728 }
4729 if (!match)
4730 return false;
4731 }
Mike Stump11289f42009-09-09 15:08:12 +00004732
Steve Naroff8e6aee52009-07-23 01:01:38 +00004733 return true;
4734 }
Mike Stump11289f42009-09-09 15:08:12 +00004735
Steve Naroff8e6aee52009-07-23 01:01:38 +00004736 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4737 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4738
Mike Stump11289f42009-09-09 15:08:12 +00004739 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004740 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004741 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004742 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4743 E = lhsOPT->qual_end(); I != E; ++I) {
4744 ObjCProtocolDecl *lhsProto = *I;
4745 bool match = false;
4746
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004747 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004748 // see if static class implements all of id's protocols, directly or
4749 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004750 // First, lhs protocols in the qualifier list must be found, direct
4751 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004752 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4753 E = rhsQID->qual_end(); J != E; ++J) {
4754 ObjCProtocolDecl *rhsProto = *J;
4755 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4756 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4757 match = true;
4758 break;
4759 }
4760 }
4761 if (!match)
4762 return false;
4763 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004764
4765 // Static class's protocols, or its super class or category protocols
4766 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4767 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4768 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4769 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4770 // This is rather dubious but matches gcc's behavior. If lhs has
4771 // no type qualifier and its class has no static protocol(s)
4772 // assume that it is mismatch.
4773 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4774 return false;
4775 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4776 LHSInheritedProtocols.begin(),
4777 E = LHSInheritedProtocols.end(); I != E; ++I) {
4778 bool match = false;
4779 ObjCProtocolDecl *lhsProto = (*I);
4780 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4781 E = rhsQID->qual_end(); J != E; ++J) {
4782 ObjCProtocolDecl *rhsProto = *J;
4783 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4784 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4785 match = true;
4786 break;
4787 }
4788 }
4789 if (!match)
4790 return false;
4791 }
4792 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004793 return true;
4794 }
4795 return false;
4796}
4797
Eli Friedman47f77112008-08-22 00:56:42 +00004798/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004799/// compatible for assignment from RHS to LHS. This handles validation of any
4800/// protocol qualifiers on the LHS or RHS.
4801///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004802bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4803 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004804 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4805 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4806
Steve Naroff1329fa02009-07-15 18:40:39 +00004807 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004808 if (LHS->isObjCUnqualifiedIdOrClass() ||
4809 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004810 return true;
4811
John McCall8b07ec22010-05-15 11:32:37 +00004812 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004813 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4814 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004815 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004816
4817 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4818 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4819 QualType(RHSOPT,0));
4820
John McCall8b07ec22010-05-15 11:32:37 +00004821 // If we have 2 user-defined types, fall into that path.
4822 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004823 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004824
Steve Naroff8e6aee52009-07-23 01:01:38 +00004825 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004826}
4827
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004828/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4829/// for providing type-safty for objective-c pointers used to pass/return
4830/// arguments in block literals. When passed as arguments, passing 'A*' where
4831/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4832/// not OK. For the return type, the opposite is not OK.
4833bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4834 const ObjCObjectPointerType *LHSOPT,
4835 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004836 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004837 return true;
4838
4839 if (LHSOPT->isObjCBuiltinType()) {
4840 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4841 }
4842
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004843 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004844 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4845 QualType(RHSOPT,0),
4846 false);
4847
4848 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4849 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4850 if (LHS && RHS) { // We have 2 user-defined types.
4851 if (LHS != RHS) {
4852 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4853 return false;
4854 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4855 return true;
4856 }
4857 else
4858 return true;
4859 }
4860 return false;
4861}
4862
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004863/// getIntersectionOfProtocols - This routine finds the intersection of set
4864/// of protocols inherited from two distinct objective-c pointer objects.
4865/// It is used to build composite qualifier list of the composite type of
4866/// the conditional expression involving two objective-c pointer objects.
4867static
4868void getIntersectionOfProtocols(ASTContext &Context,
4869 const ObjCObjectPointerType *LHSOPT,
4870 const ObjCObjectPointerType *RHSOPT,
4871 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4872
John McCall8b07ec22010-05-15 11:32:37 +00004873 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4874 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4875 assert(LHS->getInterface() && "LHS must have an interface base");
4876 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004877
4878 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4879 unsigned LHSNumProtocols = LHS->getNumProtocols();
4880 if (LHSNumProtocols > 0)
4881 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4882 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004883 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004884 Context.CollectInheritedProtocols(LHS->getInterface(),
4885 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004886 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4887 LHSInheritedProtocols.end());
4888 }
4889
4890 unsigned RHSNumProtocols = RHS->getNumProtocols();
4891 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004892 ObjCProtocolDecl **RHSProtocols =
4893 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004894 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4895 if (InheritedProtocolSet.count(RHSProtocols[i]))
4896 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4897 }
4898 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004899 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004900 Context.CollectInheritedProtocols(RHS->getInterface(),
4901 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004902 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4903 RHSInheritedProtocols.begin(),
4904 E = RHSInheritedProtocols.end(); I != E; ++I)
4905 if (InheritedProtocolSet.count((*I)))
4906 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004907 }
4908}
4909
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004910/// areCommonBaseCompatible - Returns common base class of the two classes if
4911/// one found. Note that this is O'2 algorithm. But it will be called as the
4912/// last type comparison in a ?-exp of ObjC pointer types before a
4913/// warning is issued. So, its invokation is extremely rare.
4914QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004915 const ObjCObjectPointerType *Lptr,
4916 const ObjCObjectPointerType *Rptr) {
4917 const ObjCObjectType *LHS = Lptr->getObjectType();
4918 const ObjCObjectType *RHS = Rptr->getObjectType();
4919 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4920 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4921 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004922 return QualType();
4923
John McCall8b07ec22010-05-15 11:32:37 +00004924 while ((LDecl = LDecl->getSuperClass())) {
4925 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004926 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004927 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4928 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4929
4930 QualType Result = QualType(LHS, 0);
4931 if (!Protocols.empty())
4932 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4933 Result = getObjCObjectPointerType(Result);
4934 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004935 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004936 }
4937
4938 return QualType();
4939}
4940
John McCall8b07ec22010-05-15 11:32:37 +00004941bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4942 const ObjCObjectType *RHS) {
4943 assert(LHS->getInterface() && "LHS is not an interface type");
4944 assert(RHS->getInterface() && "RHS is not an interface type");
4945
Chris Lattner49af6a42008-04-07 06:51:04 +00004946 // Verify that the base decls are compatible: the RHS must be a subclass of
4947 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004948 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004949 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004950
Chris Lattner49af6a42008-04-07 06:51:04 +00004951 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4952 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004953 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004954 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004955
Chris Lattner49af6a42008-04-07 06:51:04 +00004956 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4957 // isn't a superset.
Steve Naroffc277ad12009-07-18 15:33:26 +00004958 if (RHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004959 return true; // FIXME: should return false!
Mike Stump11289f42009-09-09 15:08:12 +00004960
John McCall8b07ec22010-05-15 11:32:37 +00004961 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4962 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00004963 LHSPI != LHSPE; LHSPI++) {
4964 bool RHSImplementsProtocol = false;
4965
4966 // If the RHS doesn't implement the protocol on the left, the types
4967 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00004968 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4969 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00004970 RHSPI != RHSPE; RHSPI++) {
4971 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00004972 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00004973 break;
4974 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004975 }
4976 // FIXME: For better diagnostics, consider passing back the protocol name.
4977 if (!RHSImplementsProtocol)
4978 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00004979 }
Steve Naroff114aecb2009-03-01 16:12:44 +00004980 // The RHS implements all protocols listed on the LHS.
4981 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00004982}
4983
Steve Naroffb7605152009-02-12 17:52:19 +00004984bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4985 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00004986 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4987 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004988
Steve Naroff7cae42b2009-07-10 23:34:53 +00004989 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00004990 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004991
4992 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4993 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00004994}
4995
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004996bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4997 return canAssignObjCInterfaces(
4998 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4999 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5000}
5001
Mike Stump11289f42009-09-09 15:08:12 +00005002/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005003/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005004/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005005/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005006bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5007 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005008 if (getLangOptions().CPlusPlus)
5009 return hasSameType(LHS, RHS);
5010
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005011 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005012}
5013
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005014bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5015 return !mergeTypes(LHS, RHS, true).isNull();
5016}
5017
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005018/// mergeTransparentUnionType - if T is a transparent union type and a member
5019/// of T is compatible with SubType, return the merged type, else return
5020/// QualType()
5021QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5022 bool OfBlockPointer,
5023 bool Unqualified) {
5024 if (const RecordType *UT = T->getAsUnionType()) {
5025 RecordDecl *UD = UT->getDecl();
5026 if (UD->hasAttr<TransparentUnionAttr>()) {
5027 for (RecordDecl::field_iterator it = UD->field_begin(),
5028 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005029 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005030 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5031 if (!MT.isNull())
5032 return MT;
5033 }
5034 }
5035 }
5036
5037 return QualType();
5038}
5039
5040/// mergeFunctionArgumentTypes - merge two types which appear as function
5041/// argument types
5042QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5043 bool OfBlockPointer,
5044 bool Unqualified) {
5045 // GNU extension: two types are compatible if they appear as a function
5046 // argument, one of the types is a transparent union type and the other
5047 // type is compatible with a union member
5048 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5049 Unqualified);
5050 if (!lmerge.isNull())
5051 return lmerge;
5052
5053 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5054 Unqualified);
5055 if (!rmerge.isNull())
5056 return rmerge;
5057
5058 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5059}
5060
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005061QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005062 bool OfBlockPointer,
5063 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005064 const FunctionType *lbase = lhs->getAs<FunctionType>();
5065 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005066 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5067 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005068 bool allLTypes = true;
5069 bool allRTypes = true;
5070
5071 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005072 QualType retType;
5073 if (OfBlockPointer)
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005074 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
5075 Unqualified);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005076 else
John McCall8c6b56f2010-12-15 01:06:38 +00005077 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5078 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005079 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005080
5081 if (Unqualified)
5082 retType = retType.getUnqualifiedType();
5083
5084 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5085 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5086 if (Unqualified) {
5087 LRetType = LRetType.getUnqualifiedType();
5088 RRetType = RRetType.getUnqualifiedType();
5089 }
5090
5091 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005092 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005093 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005094 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005095
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005096 // FIXME: double check this
5097 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5098 // rbase->getRegParmAttr() != 0 &&
5099 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005100 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5101 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005102
Douglas Gregor8c940862010-01-18 17:14:39 +00005103 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005104 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005105 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005106
John McCall8c6b56f2010-12-15 01:06:38 +00005107 // Regparm is part of the calling convention.
5108 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5109 return QualType();
5110
5111 // It's noreturn if either type is.
5112 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5113 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5114 if (NoReturn != lbaseInfo.getNoReturn())
5115 allLTypes = false;
5116 if (NoReturn != rbaseInfo.getNoReturn())
5117 allRTypes = false;
5118
5119 FunctionType::ExtInfo einfo(NoReturn,
5120 lbaseInfo.getRegParm(),
5121 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005122
Eli Friedman47f77112008-08-22 00:56:42 +00005123 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005124 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5125 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005126 unsigned lproto_nargs = lproto->getNumArgs();
5127 unsigned rproto_nargs = rproto->getNumArgs();
5128
5129 // Compatible functions must have the same number of arguments
5130 if (lproto_nargs != rproto_nargs)
5131 return QualType();
5132
5133 // Variadic and non-variadic functions aren't compatible
5134 if (lproto->isVariadic() != rproto->isVariadic())
5135 return QualType();
5136
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005137 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5138 return QualType();
5139
Eli Friedman47f77112008-08-22 00:56:42 +00005140 // Check argument compatibility
5141 llvm::SmallVector<QualType, 10> types;
5142 for (unsigned i = 0; i < lproto_nargs; i++) {
5143 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5144 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005145 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5146 OfBlockPointer,
5147 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005148 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005149
5150 if (Unqualified)
5151 argtype = argtype.getUnqualifiedType();
5152
Eli Friedman47f77112008-08-22 00:56:42 +00005153 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005154 if (Unqualified) {
5155 largtype = largtype.getUnqualifiedType();
5156 rargtype = rargtype.getUnqualifiedType();
5157 }
5158
Chris Lattner465fa322008-10-05 17:34:18 +00005159 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5160 allLTypes = false;
5161 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5162 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005163 }
5164 if (allLTypes) return lhs;
5165 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005166
5167 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5168 EPI.ExtInfo = einfo;
5169 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005170 }
5171
5172 if (lproto) allRTypes = false;
5173 if (rproto) allLTypes = false;
5174
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005175 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005176 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005177 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005178 if (proto->isVariadic()) return QualType();
5179 // Check that the types are compatible with the types that
5180 // would result from default argument promotions (C99 6.7.5.3p15).
5181 // The only types actually affected are promotable integer
5182 // types and floats, which would be passed as a different
5183 // type depending on whether the prototype is visible.
5184 unsigned proto_nargs = proto->getNumArgs();
5185 for (unsigned i = 0; i < proto_nargs; ++i) {
5186 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005187
5188 // Look at the promotion type of enum types, since that is the type used
5189 // to pass enum values.
5190 if (const EnumType *Enum = argTy->getAs<EnumType>())
5191 argTy = Enum->getDecl()->getPromotionType();
5192
Eli Friedman47f77112008-08-22 00:56:42 +00005193 if (argTy->isPromotableIntegerType() ||
5194 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5195 return QualType();
5196 }
5197
5198 if (allLTypes) return lhs;
5199 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005200
5201 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5202 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005203 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005204 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005205 }
5206
5207 if (allLTypes) return lhs;
5208 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005209 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005210}
5211
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005212QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005213 bool OfBlockPointer,
5214 bool Unqualified) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005215 // C++ [expr]: If an expression initially has the type "reference to T", the
5216 // type is adjusted to "T" prior to any further analysis, the expression
5217 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005218 // expression is an lvalue unless the reference is an rvalue reference and
5219 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005220 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5221 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005222
5223 if (Unqualified) {
5224 LHS = LHS.getUnqualifiedType();
5225 RHS = RHS.getUnqualifiedType();
5226 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005227
Eli Friedman47f77112008-08-22 00:56:42 +00005228 QualType LHSCan = getCanonicalType(LHS),
5229 RHSCan = getCanonicalType(RHS);
5230
5231 // If two types are identical, they are compatible.
5232 if (LHSCan == RHSCan)
5233 return LHS;
5234
John McCall8ccfcb52009-09-24 19:53:00 +00005235 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005236 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5237 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005238 if (LQuals != RQuals) {
5239 // If any of these qualifiers are different, we have a type
5240 // mismatch.
5241 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5242 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5243 return QualType();
5244
5245 // Exactly one GC qualifier difference is allowed: __strong is
5246 // okay if the other type has no GC qualifier but is an Objective
5247 // C object pointer (i.e. implicitly strong by default). We fix
5248 // this by pretending that the unqualified type was actually
5249 // qualified __strong.
5250 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5251 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5252 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5253
5254 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5255 return QualType();
5256
5257 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5258 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5259 }
5260 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5261 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5262 }
Eli Friedman47f77112008-08-22 00:56:42 +00005263 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005264 }
5265
5266 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005267
Eli Friedmandcca6332009-06-01 01:22:52 +00005268 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5269 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005270
Chris Lattnerfd652912008-01-14 05:45:46 +00005271 // We want to consider the two function types to be the same for these
5272 // comparisons, just force one to the other.
5273 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5274 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005275
5276 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005277 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5278 LHSClass = Type::ConstantArray;
5279 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5280 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005281
John McCall8b07ec22010-05-15 11:32:37 +00005282 // ObjCInterfaces are just specialized ObjCObjects.
5283 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5284 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5285
Nate Begemance4d7fc2008-04-18 23:10:10 +00005286 // Canonicalize ExtVector -> Vector.
5287 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5288 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005289
Chris Lattner95554662008-04-07 05:43:21 +00005290 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005291 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005292 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005293 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005294 // Compatibility is based on the underlying type, not the promotion
5295 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005296 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005297 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5298 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005299 }
John McCall9dd450b2009-09-21 23:43:11 +00005300 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005301 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5302 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005303 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005304
Eli Friedman47f77112008-08-22 00:56:42 +00005305 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005306 }
Eli Friedman47f77112008-08-22 00:56:42 +00005307
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005308 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005309 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005310#define TYPE(Class, Base)
5311#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005312#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005313#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5314#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5315#include "clang/AST/TypeNodes.def"
5316 assert(false && "Non-canonical and dependent types shouldn't get here");
5317 return QualType();
5318
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005319 case Type::LValueReference:
5320 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005321 case Type::MemberPointer:
5322 assert(false && "C++ should never be in mergeTypes");
5323 return QualType();
5324
John McCall8b07ec22010-05-15 11:32:37 +00005325 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005326 case Type::IncompleteArray:
5327 case Type::VariableArray:
5328 case Type::FunctionProto:
5329 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005330 assert(false && "Types are eliminated above");
5331 return QualType();
5332
Chris Lattnerfd652912008-01-14 05:45:46 +00005333 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005334 {
5335 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005336 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5337 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005338 if (Unqualified) {
5339 LHSPointee = LHSPointee.getUnqualifiedType();
5340 RHSPointee = RHSPointee.getUnqualifiedType();
5341 }
5342 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5343 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005344 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005345 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005346 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005347 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005348 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005349 return getPointerType(ResultType);
5350 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005351 case Type::BlockPointer:
5352 {
5353 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005354 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5355 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005356 if (Unqualified) {
5357 LHSPointee = LHSPointee.getUnqualifiedType();
5358 RHSPointee = RHSPointee.getUnqualifiedType();
5359 }
5360 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5361 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005362 if (ResultType.isNull()) return QualType();
5363 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5364 return LHS;
5365 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5366 return RHS;
5367 return getBlockPointerType(ResultType);
5368 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005369 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005370 {
5371 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5372 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5373 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5374 return QualType();
5375
5376 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5377 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005378 if (Unqualified) {
5379 LHSElem = LHSElem.getUnqualifiedType();
5380 RHSElem = RHSElem.getUnqualifiedType();
5381 }
5382
5383 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005384 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005385 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5386 return LHS;
5387 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5388 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005389 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5390 ArrayType::ArraySizeModifier(), 0);
5391 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5392 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005393 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5394 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005395 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5396 return LHS;
5397 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5398 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005399 if (LVAT) {
5400 // FIXME: This isn't correct! But tricky to implement because
5401 // the array's size has to be the size of LHS, but the type
5402 // has to be different.
5403 return LHS;
5404 }
5405 if (RVAT) {
5406 // FIXME: This isn't correct! But tricky to implement because
5407 // the array's size has to be the size of RHS, but the type
5408 // has to be different.
5409 return RHS;
5410 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005411 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5412 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005413 return getIncompleteArrayType(ResultType,
5414 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005415 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005416 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005417 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005418 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005419 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005420 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005421 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005422 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005423 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005424 case Type::Complex:
5425 // Distinct complex types are incompatible.
5426 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005427 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005428 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005429 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5430 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005431 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005432 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005433 case Type::ObjCObject: {
5434 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005435 // FIXME: This should be type compatibility, e.g. whether
5436 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005437 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5438 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5439 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005440 return LHS;
5441
Eli Friedman47f77112008-08-22 00:56:42 +00005442 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005443 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005444 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005445 if (OfBlockPointer) {
5446 if (canAssignObjCInterfacesInBlockPointer(
5447 LHS->getAs<ObjCObjectPointerType>(),
5448 RHS->getAs<ObjCObjectPointerType>()))
5449 return LHS;
5450 return QualType();
5451 }
John McCall9dd450b2009-09-21 23:43:11 +00005452 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5453 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005454 return LHS;
5455
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005456 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005457 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005458 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005459
5460 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005461}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005462
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005463/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5464/// 'RHS' attributes and returns the merged version; including for function
5465/// return types.
5466QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5467 QualType LHSCan = getCanonicalType(LHS),
5468 RHSCan = getCanonicalType(RHS);
5469 // If two types are identical, they are compatible.
5470 if (LHSCan == RHSCan)
5471 return LHS;
5472 if (RHSCan->isFunctionType()) {
5473 if (!LHSCan->isFunctionType())
5474 return QualType();
5475 QualType OldReturnType =
5476 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5477 QualType NewReturnType =
5478 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5479 QualType ResReturnType =
5480 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5481 if (ResReturnType.isNull())
5482 return QualType();
5483 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5484 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5485 // In either case, use OldReturnType to build the new function type.
5486 const FunctionType *F = LHS->getAs<FunctionType>();
5487 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005488 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5489 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005490 QualType ResultType
5491 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005492 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005493 return ResultType;
5494 }
5495 }
5496 return QualType();
5497 }
5498
5499 // If the qualifiers are different, the types can still be merged.
5500 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5501 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5502 if (LQuals != RQuals) {
5503 // If any of these qualifiers are different, we have a type mismatch.
5504 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5505 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5506 return QualType();
5507
5508 // Exactly one GC qualifier difference is allowed: __strong is
5509 // okay if the other type has no GC qualifier but is an Objective
5510 // C object pointer (i.e. implicitly strong by default). We fix
5511 // this by pretending that the unqualified type was actually
5512 // qualified __strong.
5513 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5514 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5515 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5516
5517 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5518 return QualType();
5519
5520 if (GC_L == Qualifiers::Strong)
5521 return LHS;
5522 if (GC_R == Qualifiers::Strong)
5523 return RHS;
5524 return QualType();
5525 }
5526
5527 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5528 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5529 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5530 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5531 if (ResQT == LHSBaseQT)
5532 return LHS;
5533 if (ResQT == RHSBaseQT)
5534 return RHS;
5535 }
5536 return QualType();
5537}
5538
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005539//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005540// Integer Predicates
5541//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005542
Jay Foad39c79802011-01-12 09:06:06 +00005543unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005544 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005545 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005546 if (T->isBooleanType())
5547 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005548 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005549 return (unsigned)getTypeSize(T);
5550}
5551
5552QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005553 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005554
5555 // Turn <4 x signed int> -> <4 x unsigned int>
5556 if (const VectorType *VTy = T->getAs<VectorType>())
5557 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005558 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005559
5560 // For enums, we return the unsigned version of the base type.
5561 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005562 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005563
5564 const BuiltinType *BTy = T->getAs<BuiltinType>();
5565 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005566 switch (BTy->getKind()) {
5567 case BuiltinType::Char_S:
5568 case BuiltinType::SChar:
5569 return UnsignedCharTy;
5570 case BuiltinType::Short:
5571 return UnsignedShortTy;
5572 case BuiltinType::Int:
5573 return UnsignedIntTy;
5574 case BuiltinType::Long:
5575 return UnsignedLongTy;
5576 case BuiltinType::LongLong:
5577 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005578 case BuiltinType::Int128:
5579 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005580 default:
5581 assert(0 && "Unexpected signed integer type");
5582 return QualType();
5583 }
5584}
5585
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005586ExternalASTSource::~ExternalASTSource() { }
5587
5588void ExternalASTSource::PrintStats() { }
Chris Lattnerecd79c62009-06-14 00:45:47 +00005589
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005590ASTMutationListener::~ASTMutationListener() { }
5591
Chris Lattnerecd79c62009-06-14 00:45:47 +00005592
5593//===----------------------------------------------------------------------===//
5594// Builtin Type Computation
5595//===----------------------------------------------------------------------===//
5596
5597/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005598/// pointer over the consumed characters. This returns the resultant type. If
5599/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5600/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5601/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005602///
5603/// RequiresICE is filled in on return to indicate whether the value is required
5604/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005605static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005606 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005607 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005608 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005609 // Modifiers.
5610 int HowLong = 0;
5611 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005612 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005613
Chris Lattnerdc226c22010-10-01 22:42:38 +00005614 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005615 bool Done = false;
5616 while (!Done) {
5617 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005618 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005619 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005620 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005621 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005622 case 'S':
5623 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5624 assert(!Signed && "Can't use 'S' modifier multiple times!");
5625 Signed = true;
5626 break;
5627 case 'U':
5628 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5629 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5630 Unsigned = true;
5631 break;
5632 case 'L':
5633 assert(HowLong <= 2 && "Can't have LLLL modifier");
5634 ++HowLong;
5635 break;
5636 }
5637 }
5638
5639 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005640
Chris Lattnerecd79c62009-06-14 00:45:47 +00005641 // Read the base type.
5642 switch (*Str++) {
5643 default: assert(0 && "Unknown builtin type letter!");
5644 case 'v':
5645 assert(HowLong == 0 && !Signed && !Unsigned &&
5646 "Bad modifiers used with 'v'!");
5647 Type = Context.VoidTy;
5648 break;
5649 case 'f':
5650 assert(HowLong == 0 && !Signed && !Unsigned &&
5651 "Bad modifiers used with 'f'!");
5652 Type = Context.FloatTy;
5653 break;
5654 case 'd':
5655 assert(HowLong < 2 && !Signed && !Unsigned &&
5656 "Bad modifiers used with 'd'!");
5657 if (HowLong)
5658 Type = Context.LongDoubleTy;
5659 else
5660 Type = Context.DoubleTy;
5661 break;
5662 case 's':
5663 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5664 if (Unsigned)
5665 Type = Context.UnsignedShortTy;
5666 else
5667 Type = Context.ShortTy;
5668 break;
5669 case 'i':
5670 if (HowLong == 3)
5671 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5672 else if (HowLong == 2)
5673 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5674 else if (HowLong == 1)
5675 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5676 else
5677 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5678 break;
5679 case 'c':
5680 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5681 if (Signed)
5682 Type = Context.SignedCharTy;
5683 else if (Unsigned)
5684 Type = Context.UnsignedCharTy;
5685 else
5686 Type = Context.CharTy;
5687 break;
5688 case 'b': // boolean
5689 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5690 Type = Context.BoolTy;
5691 break;
5692 case 'z': // size_t.
5693 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5694 Type = Context.getSizeType();
5695 break;
5696 case 'F':
5697 Type = Context.getCFConstantStringType();
5698 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005699 case 'G':
5700 Type = Context.getObjCIdType();
5701 break;
5702 case 'H':
5703 Type = Context.getObjCSelType();
5704 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005705 case 'a':
5706 Type = Context.getBuiltinVaListType();
5707 assert(!Type.isNull() && "builtin va list type not initialized!");
5708 break;
5709 case 'A':
5710 // This is a "reference" to a va_list; however, what exactly
5711 // this means depends on how va_list is defined. There are two
5712 // different kinds of va_list: ones passed by value, and ones
5713 // passed by reference. An example of a by-value va_list is
5714 // x86, where va_list is a char*. An example of by-ref va_list
5715 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5716 // we want this argument to be a char*&; for x86-64, we want
5717 // it to be a __va_list_tag*.
5718 Type = Context.getBuiltinVaListType();
5719 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005720 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005721 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005722 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005723 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005724 break;
5725 case 'V': {
5726 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005727 unsigned NumElements = strtoul(Str, &End, 10);
5728 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005729 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005730
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005731 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5732 RequiresICE, false);
5733 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005734
5735 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005736 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005737 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005738 break;
5739 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005740 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005741 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5742 false);
5743 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005744 Type = Context.getComplexType(ElementType);
5745 break;
5746 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005747 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005748 Type = Context.getFILEType();
5749 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005750 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005751 return QualType();
5752 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005753 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005754 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005755 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005756 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005757 else
5758 Type = Context.getjmp_bufType();
5759
Mike Stump2adb4da2009-07-28 23:47:15 +00005760 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005761 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005762 return QualType();
5763 }
5764 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005765 }
Mike Stump11289f42009-09-09 15:08:12 +00005766
Chris Lattnerdc226c22010-10-01 22:42:38 +00005767 // If there are modifiers and if we're allowed to parse them, go for it.
5768 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005769 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005770 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005771 default: Done = true; --Str; break;
5772 case '*':
5773 case '&': {
5774 // Both pointers and references can have their pointee types
5775 // qualified with an address space.
5776 char *End;
5777 unsigned AddrSpace = strtoul(Str, &End, 10);
5778 if (End != Str && AddrSpace != 0) {
5779 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5780 Str = End;
5781 }
5782 if (c == '*')
5783 Type = Context.getPointerType(Type);
5784 else
5785 Type = Context.getLValueReferenceType(Type);
5786 break;
5787 }
5788 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5789 case 'C':
5790 Type = Type.withConst();
5791 break;
5792 case 'D':
5793 Type = Context.getVolatileType(Type);
5794 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005795 }
5796 }
Chris Lattner84733392010-10-01 07:13:18 +00005797
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005798 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005799 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005800
Chris Lattnerecd79c62009-06-14 00:45:47 +00005801 return Type;
5802}
5803
5804/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005805QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005806 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005807 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005808 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005809
Chris Lattnerecd79c62009-06-14 00:45:47 +00005810 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005811
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005812 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005813 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005814 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5815 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005816 if (Error != GE_None)
5817 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005818
5819 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5820
Chris Lattnerecd79c62009-06-14 00:45:47 +00005821 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005822 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005823 if (Error != GE_None)
5824 return QualType();
5825
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005826 // If this argument is required to be an IntegerConstantExpression and the
5827 // caller cares, fill in the bitmask we return.
5828 if (RequiresICE && IntegerConstantArgs)
5829 *IntegerConstantArgs |= 1 << ArgTypes.size();
5830
Chris Lattnerecd79c62009-06-14 00:45:47 +00005831 // Do array -> pointer decay. The builtin should use the decayed type.
5832 if (Ty->isArrayType())
5833 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005834
Chris Lattnerecd79c62009-06-14 00:45:47 +00005835 ArgTypes.push_back(Ty);
5836 }
5837
5838 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5839 "'.' should only occur at end of builtin type list!");
5840
John McCall991eb4b2010-12-21 00:44:39 +00005841 FunctionType::ExtInfo EI;
5842 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5843
5844 bool Variadic = (TypeStr[0] == '.');
5845
5846 // We really shouldn't be making a no-proto type here, especially in C++.
5847 if (ArgTypes.empty() && Variadic)
5848 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005849
John McCalldb40c7f2010-12-14 08:05:40 +00005850 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005851 EPI.ExtInfo = EI;
5852 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005853
5854 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005855}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005856
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005857GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5858 GVALinkage External = GVA_StrongExternal;
5859
5860 Linkage L = FD->getLinkage();
5861 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5862 FD->getType()->getLinkage() == UniqueExternalLinkage)
5863 L = UniqueExternalLinkage;
5864
5865 switch (L) {
5866 case NoLinkage:
5867 case InternalLinkage:
5868 case UniqueExternalLinkage:
5869 return GVA_Internal;
5870
5871 case ExternalLinkage:
5872 switch (FD->getTemplateSpecializationKind()) {
5873 case TSK_Undeclared:
5874 case TSK_ExplicitSpecialization:
5875 External = GVA_StrongExternal;
5876 break;
5877
5878 case TSK_ExplicitInstantiationDefinition:
5879 return GVA_ExplicitTemplateInstantiation;
5880
5881 case TSK_ExplicitInstantiationDeclaration:
5882 case TSK_ImplicitInstantiation:
5883 External = GVA_TemplateInstantiation;
5884 break;
5885 }
5886 }
5887
5888 if (!FD->isInlined())
5889 return External;
5890
5891 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5892 // GNU or C99 inline semantics. Determine whether this symbol should be
5893 // externally visible.
5894 if (FD->isInlineDefinitionExternallyVisible())
5895 return External;
5896
5897 // C99 inline semantics, where the symbol is not externally visible.
5898 return GVA_C99Inline;
5899 }
5900
5901 // C++0x [temp.explicit]p9:
5902 // [ Note: The intent is that an inline function that is the subject of
5903 // an explicit instantiation declaration will still be implicitly
5904 // instantiated when used so that the body can be considered for
5905 // inlining, but that no out-of-line copy of the inline function would be
5906 // generated in the translation unit. -- end note ]
5907 if (FD->getTemplateSpecializationKind()
5908 == TSK_ExplicitInstantiationDeclaration)
5909 return GVA_C99Inline;
5910
5911 return GVA_CXXInline;
5912}
5913
5914GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5915 // If this is a static data member, compute the kind of template
5916 // specialization. Otherwise, this variable is not part of a
5917 // template.
5918 TemplateSpecializationKind TSK = TSK_Undeclared;
5919 if (VD->isStaticDataMember())
5920 TSK = VD->getTemplateSpecializationKind();
5921
5922 Linkage L = VD->getLinkage();
5923 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5924 VD->getType()->getLinkage() == UniqueExternalLinkage)
5925 L = UniqueExternalLinkage;
5926
5927 switch (L) {
5928 case NoLinkage:
5929 case InternalLinkage:
5930 case UniqueExternalLinkage:
5931 return GVA_Internal;
5932
5933 case ExternalLinkage:
5934 switch (TSK) {
5935 case TSK_Undeclared:
5936 case TSK_ExplicitSpecialization:
5937 return GVA_StrongExternal;
5938
5939 case TSK_ExplicitInstantiationDeclaration:
5940 llvm_unreachable("Variable should not be instantiated");
5941 // Fall through to treat this like any other instantiation.
5942
5943 case TSK_ExplicitInstantiationDefinition:
5944 return GVA_ExplicitTemplateInstantiation;
5945
5946 case TSK_ImplicitInstantiation:
5947 return GVA_TemplateInstantiation;
5948 }
5949 }
5950
5951 return GVA_StrongExternal;
5952}
5953
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00005954bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005955 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5956 if (!VD->isFileVarDecl())
5957 return false;
5958 } else if (!isa<FunctionDecl>(D))
5959 return false;
5960
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00005961 // Weak references don't produce any output by themselves.
5962 if (D->hasAttr<WeakRefAttr>())
5963 return false;
5964
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005965 // Aliases and used decls are required.
5966 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5967 return true;
5968
5969 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5970 // Forward declarations aren't required.
5971 if (!FD->isThisDeclarationADefinition())
5972 return false;
5973
5974 // Constructors and destructors are required.
5975 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5976 return true;
5977
5978 // The key function for a class is required.
5979 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5980 const CXXRecordDecl *RD = MD->getParent();
5981 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5982 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5983 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5984 return true;
5985 }
5986 }
5987
5988 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5989
5990 // static, static inline, always_inline, and extern inline functions can
5991 // always be deferred. Normal inline functions can be deferred in C99/C++.
5992 // Implicit template instantiations can also be deferred in C++.
5993 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5994 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5995 return false;
5996 return true;
5997 }
5998
5999 const VarDecl *VD = cast<VarDecl>(D);
6000 assert(VD->isFileVarDecl() && "Expected file scoped var");
6001
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006002 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6003 return false;
6004
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006005 // Structs that have non-trivial constructors or destructors are required.
6006
6007 // FIXME: Handle references.
6008 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6009 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006010 if (RD->hasDefinition() &&
6011 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006012 return true;
6013 }
6014 }
6015
6016 GVALinkage L = GetGVALinkageForVariable(VD);
6017 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6018 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6019 return false;
6020 }
6021
6022 return true;
6023}
Charles Davis53c59df2010-08-16 03:33:14 +00006024
Charles Davis99202b32010-11-09 18:04:24 +00006025CallingConv ASTContext::getDefaultMethodCallConv() {
6026 // Pass through to the C++ ABI object
6027 return ABI->getDefaultMethodCallConv();
6028}
6029
Jay Foad39c79802011-01-12 09:06:06 +00006030bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006031 // Pass through to the C++ ABI object
6032 return ABI->isNearlyEmpty(RD);
6033}
6034
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006035MangleContext *ASTContext::createMangleContext() {
6036 switch (Target.getCXXABI()) {
6037 case CXXABI_ARM:
6038 case CXXABI_Itanium:
6039 return createItaniumMangleContext(*this, getDiagnostics());
6040 case CXXABI_Microsoft:
6041 return createMicrosoftMangleContext(*this, getDiagnostics());
6042 }
6043 assert(0 && "Unsupported ABI");
6044 return 0;
6045}
6046
Charles Davis53c59df2010-08-16 03:33:14 +00006047CXXABI::~CXXABI() {}