blob: d96d07990850adc5440e1db1adda213ed913b7e8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000034
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Douglas Gregor18274032010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor3e1274f2010-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 Gregor61c4d282011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-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 Gregor61c4d282011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-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 Gregor3e1274f2010-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 Foad4ba2a172011-01-12 09:06:06 +000090 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-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 Gregor6952f1e2011-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 Gregor3e1274f2010-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 Gregor61c4d282011-01-05 15:48:55 +0000155 TTP->getPosition(),
156 TTP->isParameterPack(),
157 0,
Douglas Gregor3e1274f2010-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 Davis071cc7d2010-08-16 03:33:14 +0000175CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000176 if (!LangOpts.CPlusPlus) return 0;
177
Charles Davis20cf7172010-08-19 02:18:14 +0000178 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000179 case CXXABI_ARM:
180 return CreateARMCXXABI(*this);
181 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000182 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000183 case CXXABI_Microsoft:
184 return CreateMicrosoftCXXABI(*this);
185 }
John McCallee79a4c2010-08-21 22:46:04 +0000186 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000187}
188
Chris Lattner61710852008-10-05 17:34:18 +0000189ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000190 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000191 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000192 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000193 unsigned size_reserve) :
John McCallef990012010-06-11 11:07:21 +0000194 TemplateSpecializationTypes(this_()),
195 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000196 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
197 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000198 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000199 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
John McCallbf1a0282010-06-04 23:28:52 +0000200 NullTypeSourceInfo(QualType()),
Charles Davis071cc7d2010-08-16 03:33:14 +0000201 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000202 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000203 BuiltinInfo(builtins),
204 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000205 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000206 LastSDM(0, 0),
207 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000208 ObjCIdRedefinitionType = QualType();
209 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000210 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000211 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000212 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000213 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000214}
215
Reid Spencer5f016e22007-07-11 17:01:13 +0000216ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000217 // Release the DenseMaps associated with DeclContext objects.
218 // FIXME: Is this the ideal solution?
219 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000220
Douglas Gregor63fe86b2010-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 Gregor00545312010-05-23 18:26:36 +0000224
Douglas Gregor7d10b7e2010-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 Kremenek3478eb62010-02-11 07:12:28 +0000230
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000231 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-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 Kremenekdcfcfbe2010-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 Gregor63200642010-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 Gregorab452ba2009-03-26 23:50:42 +0000252
Douglas Gregor00545312010-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 Stump1eb44332009-09-09 15:08:12 +0000257void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000258ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
259 ExternalSource.reset(Source.take());
260}
261
Reid Spencer5f016e22007-07-11 17:01:13 +0000262void ASTContext::PrintStats() const {
263 fprintf(stderr, "*** AST Context Stats:\n");
264 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000265
Douglas Gregordbe833d2009-05-26 14:40:08 +0000266 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000267#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000268#define ABSTRACT_TYPE(Name, Parent)
269#include "clang/AST/TypeNodes.def"
270 0 // Extra
271 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000272
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
274 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000275 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 }
277
Douglas Gregordbe833d2009-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 Stump1eb44332009-09-09 15:08:12 +0000287
Douglas Gregordbe833d2009-05-26 14:40:08 +0000288 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000289
Douglas Gregor4923aa22010-07-02 20:37:36 +0000290 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000291 fprintf(stderr, " %u/%u implicit default constructors created\n",
292 NumImplicitDefaultConstructorsDeclared,
293 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000294 fprintf(stderr, " %u/%u implicit copy constructors created\n",
295 NumImplicitCopyConstructorsDeclared,
296 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000297 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
298 NumImplicitCopyAssignmentOperatorsDeclared,
299 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000300 fprintf(stderr, " %u/%u implicit destructors created\n",
301 NumImplicitDestructorsDeclared, NumImplicitDestructors);
302
Douglas Gregor2cf26342009-04-09 22:27:44 +0000303 if (ExternalSource.get()) {
304 fprintf(stderr, "\n");
305 ExternalSource->PrintStats();
306 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000307
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000308 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000309}
310
311
John McCalle27ec8a2009-10-23 23:03:21 +0000312void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000313 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000314 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000315 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000316}
317
Reid Spencer5f016e22007-07-11 17:01:13 +0000318void ASTContext::InitBuiltinTypes() {
319 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 // C99 6.2.5p19.
322 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 // C99 6.2.5p2.
325 InitBuiltinType(BoolTy, BuiltinType::Bool);
326 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000327 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 InitBuiltinType(CharTy, BuiltinType::Char_S);
329 else
330 InitBuiltinType(CharTy, BuiltinType::Char_U);
331 // C99 6.2.5p4.
332 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 Stump1eb44332009-09-09 15:08:12 +0000337
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 // C99 6.2.5p6.
339 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 Stump1eb44332009-09-09 15:08:12 +0000344
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 // C99 6.2.5p10.
346 InitBuiltinType(FloatTy, BuiltinType::Float);
347 InitBuiltinType(DoubleTy, BuiltinType::Double);
348 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000349
Chris Lattner2df9ced2009-04-30 02:43:43 +0000350 // GNU extension, 128-bit integers.
351 InitBuiltinType(Int128Ty, BuiltinType::Int128);
352 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
353
Chris Lattner3f59c972010-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 Lattner3a250322009-02-26 23:43:47 +0000360 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000361
Alisdair Meredithf5c209d2009-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 Gregor898574e2008-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 Gregor8e9bebd2008-10-21 16:13:35 +0000378
John McCall2a984ca2010-10-12 00:20:44 +0000379 // Placeholder type for functions.
380 InitBuiltinType(OverloadTy, BuiltinType::Overload);
381
Mike Stump1eb44332009-09-09 15:08:12 +0000382 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000383 // not yet been deduced.
John McCall2a984ca2010-10-12 00:20:44 +0000384 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // C99 6.2.5p11.
387 FloatComplexTy = getComplexType(FloatTy);
388 DoubleComplexTy = getComplexType(DoubleTy);
389 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000390
Steve Naroff7e219e42007-10-15 14:41:52 +0000391 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Steve Naroffde2e22d2009-07-15 18:40:39 +0000393 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
394 ObjCIdTypedefType = QualType();
395 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000396 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000398 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000399 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
400 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000401 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000402
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000403 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000405 // void * type
406 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000407
408 // nullptr type (C++0x 2.14.7)
409 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000410}
411
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000412Diagnostic &ASTContext::getDiagnostics() const {
413 return SourceMgr.getDiagnostics();
414}
415
Douglas Gregor63200642010-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 Gregor251b4ff2009-10-08 07:24:58 +0000436MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000437ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000438 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000439 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000440 = InstantiatedFromStaticDataMember.find(Var);
441 if (Pos == InstantiatedFromStaticDataMember.end())
442 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Douglas Gregor7caa6822009-07-24 20:34:43 +0000444 return Pos->second;
445}
446
Mike Stump1eb44332009-09-09 15:08:12 +0000447void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000448ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000449 TemplateSpecializationKind TSK,
450 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-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 Gregor251b4ff2009-10-08 07:24:58 +0000455 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000456 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000457}
458
John McCall7ba107a2009-11-18 02:36:19 +0000459NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000460ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000461 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000462 = InstantiatedFromUsingDecl.find(UUD);
463 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000464 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Anders Carlsson0d8df782009-08-29 19:37:28 +0000466 return Pos->second;
467}
468
469void
John McCalled976492009-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 Carlsson0d8df782009-08-29 19:37:28 +0000494}
495
Anders Carlssond8b285f2009-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 Stump1eb44332009-09-09 15:08:12 +0000501
Anders Carlssond8b285f2009-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 Stump1eb44332009-09-09 15:08:12 +0000511
Anders Carlssond8b285f2009-09-01 04:26:58 +0000512 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
513}
514
Douglas Gregor7d10b7e2010-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 Kyrtzidisc91e9f42010-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 Gregor7d10b7e2010-03-02 23:58:15 +0000545void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
546 const CXXMethodDecl *Overridden) {
547 OverriddenMethods[Method].push_back(Overridden);
548}
549
Chris Lattner464175b2007-07-18 17:52:12 +0000550//===----------------------------------------------------------------------===//
551// Type Sizing and Analysis
552//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000553
Chris Lattnerb7cfe882008-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 McCall183700f2009-09-21 23:43:11 +0000557 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-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 Dyck8b752f12010-01-27 17:10:57 +0000567/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-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 Redl5d484e82009-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 Foad4ba2a172011-01-12 09:06:06 +0000572CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000573 unsigned Align = Target.getCharWidth();
574
John McCall4081a5c2010-10-08 18:24:19 +0000575 bool UseAlignAttrOnly = false;
576 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
577 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000578
John McCall4081a5c2010-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 McCallba4f5d52011-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 McCall4081a5c2010-10-08 18:24:19 +0000595 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000596 // do nothing
597
John McCall4081a5c2010-10-08 18:24:19 +0000598 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000599 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000600 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-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 McCall3b657512011-01-19 10:06:00 +0000607 // Adjust alignments of declarations with array type by the
608 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000609 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-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 Friedmandcdafb62009-02-22 02:56:25 +0000617
John McCall3b657512011-01-19 10:06:00 +0000618 // Walk through any array types while we're at it.
619 T = getBaseElementType(arrayType);
620 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000621 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
622 }
John McCallba4f5d52011-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 Davis05f62472010-02-23 04:52:00 +0000647 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000648 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000649
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000650 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000651}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000652
John McCallea1471e2010-05-20 01:18:31 +0000653std::pair<CharUnits, CharUnits>
654ASTContext::getTypeInfoInChars(const Type *T) {
655 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000656 return std::make_pair(toCharUnitsFromBits(Info.first),
657 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000658}
659
660std::pair<CharUnits, CharUnits>
661ASTContext::getTypeInfoInChars(QualType T) {
662 return getTypeInfoInChars(T.getTypePtr());
663}
664
Chris Lattnera7674d82007-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 McCall0953e762009-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 Lattnerd2d2a112007-07-14 01:29:45 +0000671std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000672ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000673 uint64_t Width=0;
674 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000675 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000676#define TYPE(Class, Base)
677#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000678#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000679#define DEPENDENT_TYPE(Class, Base) case Type::Class:
680#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000681 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000682 break;
683
Chris Lattner692233e2007-07-13 22:27:08 +0000684 case Type::FunctionNoProto:
685 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000686 // GCC extension: alignof(function) = 32 bits
687 Width = 0;
688 Align = 32;
689 break;
690
Douglas Gregor72564e72009-02-26 23:50:07 +0000691 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000692 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000693 Width = 0;
694 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
695 break;
696
Steve Narofffb22d962007-08-30 01:06:46 +0000697 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000698 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Chris Lattner98be4942008-03-05 18:54:05 +0000700 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000701 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000702 Align = EltInfo.second;
703 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000704 }
Nate Begeman213541a2008-04-18 23:10:10 +0000705 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000706 case Type::Vector: {
Chris Lattner9fcfe922009-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 Friedman4bd998b2008-05-30 09:31:38 +0000710 Align = Width;
Nate Begeman6fe7c8a2009-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 Gohman8eefcd32010-04-21 23:32:43 +0000713 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000714 Align = llvm::NextPowerOf2(Align);
715 Width = llvm::RoundUpToAlignment(Width, Align);
716 }
Chris Lattner030d8842007-07-19 22:06:24 +0000717 break;
718 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000719
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000720 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000721 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000722 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000723 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000724 // GCC extension: alignof(void) = 8 bits.
725 Width = 0;
726 Align = 8;
727 break;
728
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000729 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000730 Width = Target.getBoolWidth();
731 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000732 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000733 case BuiltinType::Char_S:
734 case BuiltinType::Char_U:
735 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000736 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000737 Width = Target.getCharWidth();
738 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000739 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000740 case BuiltinType::WChar_S:
741 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000742 Width = Target.getWCharWidth();
743 Align = Target.getWCharAlign();
744 break;
Alisdair Meredithf5c209d2009-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 Lattner692233e2007-07-13 22:27:08 +0000753 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000754 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000755 Width = Target.getShortWidth();
756 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000757 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000758 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000759 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000760 Width = Target.getIntWidth();
761 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000762 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000763 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000764 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000765 Width = Target.getLongWidth();
766 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000767 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000768 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000769 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000770 Width = Target.getLongLongWidth();
771 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000772 break;
Chris Lattnerec16cb92009-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 Lattner6f62c2a2007-12-19 19:23:28 +0000778 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000779 Width = Target.getFloatWidth();
780 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000781 break;
782 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000783 Width = Target.getDoubleWidth();
784 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000785 break;
786 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000787 Width = Target.getLongDoubleWidth();
788 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000789 break;
Sebastian Redl6e8ed162009-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 Redl1590d9c2009-05-27 19:34:06 +0000793 break;
Fariborz Jahaniane04f5fc2010-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 Lattnera7674d82007-07-13 22:13:22 +0000800 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000801 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000802 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000803 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000804 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000805 break;
Steve Naroff485eeff2008-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 Redl5d484e82009-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 Lattnerf72a4432008-03-08 08:34:58 +0000821 case Type::Pointer: {
822 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000823 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000824 Align = Target.getPointerAlign(AS);
825 break;
826 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000827 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000828 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000829 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000830 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000831 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000832 Align = PtrDiffInfo.second;
833 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000834 }
Chris Lattner5d2a6302007-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 Stump1eb44332009-09-09 15:08:12 +0000838 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000839 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000840 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000841 Align = EltInfo.second;
842 break;
843 }
John McCallc12c5bb2010-05-15 11:32:37 +0000844 case Type::ObjCObject:
845 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000846 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000847 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000848 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
849 Width = Layout.getSize();
850 Align = Layout.getAlignment();
851 break;
852 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000853 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000854 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000855 const TagType *TT = cast<TagType>(T);
856
857 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000858 Width = 1;
859 Align = 1;
860 break;
861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Daniel Dunbar1d751182008-11-08 05:48:37 +0000863 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000864 return getTypeInfo(ET->getDecl()->getIntegerType());
865
Daniel Dunbar1d751182008-11-08 05:48:37 +0000866 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000867 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
868 Width = Layout.getSize();
869 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000870 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000871 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000872
Chris Lattner9fcfe922009-10-22 05:17:15 +0000873 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000874 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
875 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000876
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000877 case Type::Paren:
878 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
879
Douglas Gregor18857642009-04-30 17:32:17 +0000880 case Type::Typedef: {
881 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-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 Gregor7532dc62009-03-30 22:58:21 +0000886 break;
Chris Lattner71763312008-04-06 22:05:18 +0000887 }
Douglas Gregor18857642009-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 Carlsson395b4752009-06-24 19:06:50 +0000896 case Type::Decltype:
897 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
898 .getTypePtr());
899
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000900 case Type::Elaborated:
901 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000902
John McCall9d156a72011-01-06 01:58:22 +0000903 case Type::Attributed:
904 return getTypeInfo(
905 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
906
Douglas Gregor18857642009-04-30 17:32:17 +0000907 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000908 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-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 Stump1eb44332009-09-09 15:08:12 +0000915
Chris Lattner464175b2007-07-18 17:52:12 +0000916 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000917 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000918}
919
Ken Dyckeb6f5dc2011-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 Dyckbdc601b2009-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 Foad4ba2a172011-01-12 09:06:06 +0000927CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000928 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000929}
Jay Foad4ba2a172011-01-12 09:06:06 +0000930CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000931 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000932}
933
Ken Dyck16e20cc2010-01-26 17:25:18 +0000934/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000935/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000936CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000937 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000938}
Jay Foad4ba2a172011-01-12 09:06:06 +0000939CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000940 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000941}
942
Chris Lattner34ebde42009-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 Foad4ba2a172011-01-12 09:06:06 +0000947unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +0000948 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000949
950 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000951 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-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 Lattner34ebde42009-01-27 18:08:34 +0000957 return ABIAlign;
958}
959
Fariborz Jahanian8e6ac1d2009-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 Foad4ba2a172011-01-12 09:06:06 +0000964 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-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 Jahanian8e6ac1d2009-06-04 01:19:09 +0000971}
972
Fariborz Jahanian2c18bb72010-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 Jahanian98200742009-05-12 18:14:29 +0000978///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000979void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
980 bool leafClass,
Jay Foad4ba2a172011-01-12 09:06:06 +0000981 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-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 Jahanian11062e12010-02-19 00:31:17 +0000987 Ivars.push_back(*I);
988 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +0000989 else
990 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +0000991}
992
Fariborz Jahaniane23fa2d2009-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 Jahanian432a8892010-02-12 19:27:33 +0000996 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000997 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-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 Jahaniane23fa2d2009-10-30 01:13:23 +00001002 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001003 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001004 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001005 PE = Proto->protocol_end(); P != PE; ++P) {
1006 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001007 CollectInheritedProtocols(*P, Protocols);
1008 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001009 }
Fariborz Jahaniane23fa2d2009-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 Kramerb170ca52010-04-27 17:47:25 +00001020 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001021 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001022 PE = OC->protocol_end(); P != PE; ++P) {
1023 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001024 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-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 Kramerb170ca52010-04-27 17:47:25 +00001029 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-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 Jahanian432a8892010-02-12 19:27:33 +00001033 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-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 Jahaniane23fa2d2009-10-30 01:13:23 +00001038 }
1039}
1040
Jay Foad4ba2a172011-01-12 09:06:06 +00001041unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001042 unsigned count = 0;
1043 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001044 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1045 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001046 count += CDecl->ivar_size();
1047
Fariborz Jahanian3bfacdf2010-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 Kramerb170ca52010-04-27 17:47:25 +00001051 count += ImplDecl->ivar_size();
1052
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001053 return count;
1054}
1055
Argyrios Kyrtzidis8a1d7222009-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 Jahanian1ceee5c2010-12-01 22:29:46 +00001086/// \brief Get the copy initialization expression of VarDecl,or NULL if
1087/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001088Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001089 assert(VD && "Passed null params");
1090 assert(VD->hasAttr<BlocksAttr>() &&
1091 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001092 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001093 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-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 Jahaniand016ec22010-12-06 17:28:17 +00001100 assert(VD->hasAttr<BlocksAttr>() &&
1101 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001102 BlockVarCopyInits[VD] = Init;
1103}
1104
John McCalla93c9342009-12-07 02:54:59 +00001105/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001106///
John McCalla93c9342009-12-07 02:54:59 +00001107/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-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 McCalla93c9342009-12-07 02:54:59 +00001113TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001114 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001115 if (!DataSize)
1116 DataSize = TypeLoc::getFullDataSizeForType(T);
1117 else
1118 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001119 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001120
John McCalla93c9342009-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 Kyrtzidisb17166c2009-08-19 01:27:32 +00001125}
1126
John McCalla93c9342009-12-07 02:54:59 +00001127TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001128 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001129 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001130 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001131 return DI;
1132}
1133
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001134const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001135ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001136 return getObjCLayout(D, 0);
1137}
1138
1139const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001140ASTContext::getASTObjCImplementationLayout(
1141 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001142 return getObjCLayout(D->getClassInterface(), D);
1143}
1144
Chris Lattnera7674d82007-07-13 22:13:22 +00001145//===----------------------------------------------------------------------===//
1146// Type creation/memoization methods
1147//===----------------------------------------------------------------------===//
1148
Jay Foad4ba2a172011-01-12 09:06:06 +00001149QualType
John McCall3b657512011-01-19 10:06:00 +00001150ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1151 unsigned fastQuals = quals.getFastQualifiers();
1152 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001153
1154 // Check if we've already instantiated this type.
1155 llvm::FoldingSetNodeID ID;
John McCall3b657512011-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 McCall0953e762009-09-24 19:53:00 +00001161 }
1162
John McCall3b657512011-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 McCall0953e762009-09-24 19:53:00 +00001177}
1178
Jay Foad4ba2a172011-01-12 09:06:06 +00001179QualType
1180ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001181 QualType CanT = getCanonicalType(T);
1182 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001183 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001184
John McCall0953e762009-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 Stump1eb44332009-09-09 15:08:12 +00001189
John McCall0953e762009-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 Stump1eb44332009-09-09 15:08:12 +00001195
John McCall0953e762009-09-24 19:53:00 +00001196 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001197}
1198
Chris Lattnerb7d25532009-02-18 22:53:11 +00001199QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001200 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001201 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001202 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001203 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001204
John McCall7f040a92010-12-24 02:08:15 +00001205 if (const PointerType *ptr = T->getAs<PointerType>()) {
1206 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001207 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001208 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1209 return getPointerType(ResultType);
1210 }
1211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
John McCall0953e762009-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 Stump1eb44332009-09-09 15:08:12 +00001217
John McCall0953e762009-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 Stump1eb44332009-09-09 15:08:12 +00001223
John McCall0953e762009-09-24 19:53:00 +00001224 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001225}
Chris Lattnera7674d82007-07-13 22:13:22 +00001226
John McCalle6a365d2010-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
Reid Spencer5f016e22007-07-11 17:01:13 +00001246/// getComplexType - Return the uniqued reference to the type for a complex
1247/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001248QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Stump1eb44332009-09-09 15:08:12 +00001253
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 void *InsertPos = 0;
1255 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1256 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Reid Spencer5f016e22007-07-11 17:01:13 +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 McCall467b27b2009-10-22 20:10:53 +00001261 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001262 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 // Get the new insert position for the node we care about.
1265 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001266 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 }
John McCall6b304a02009-09-24 23:30:46 +00001268 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 Types.push_back(New);
1270 ComplexTypes.InsertNode(New, InsertPos);
1271 return QualType(New, 0);
1272}
1273
Reid Spencer5f016e22007-07-11 17:01:13 +00001274/// getPointerType - Return the uniqued reference to the type for a pointer to
1275/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001276QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 // Unique pointers, to guarantee there is only one pointer of a particular
1278 // structure.
1279 llvm::FoldingSetNodeID ID;
1280 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 void *InsertPos = 0;
1283 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1284 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 // If the pointee type isn't canonical, this won't be a canonical type either,
1287 // so fill in the canonical type field.
1288 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001289 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001290 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 // Get the new insert position for the node we care about.
1293 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001294 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 }
John McCall6b304a02009-09-24 23:30:46 +00001296 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 Types.push_back(New);
1298 PointerTypes.InsertNode(New, InsertPos);
1299 return QualType(New, 0);
1300}
1301
Mike Stump1eb44332009-09-09 15:08:12 +00001302/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001303/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001304QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-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 Naroff5618bd42008-08-27 16:04:49 +00001307 // structure.
1308 llvm::FoldingSetNodeID ID;
1309 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Steve Naroff5618bd42008-08-27 16:04:49 +00001311 void *InsertPos = 0;
1312 if (BlockPointerType *PT =
1313 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1314 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001315
1316 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001317 // type either so fill in the canonical type field.
1318 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001319 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001320 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Steve Naroff5618bd42008-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 Yasskinc6ed7292010-12-23 01:01:28 +00001325 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001326 }
John McCall6b304a02009-09-24 23:30:46 +00001327 BlockPointerType *New
1328 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001329 Types.push_back(New);
1330 BlockPointerTypes.InsertNode(New, InsertPos);
1331 return QualType(New, 0);
1332}
1333
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001334/// getLValueReferenceType - Return the uniqued reference to the type for an
1335/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001336QualType
1337ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 // Unique pointers, to guarantee there is only one pointer of a particular
1339 // structure.
1340 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001341 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001342
1343 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001344 if (LValueReferenceType *RT =
1345 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001347
John McCall54e14c42009-10-22 22:37:11 +00001348 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1349
Reid Spencer5f016e22007-07-11 17:01:13 +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 McCall54e14c42009-10-22 22:37:11 +00001353 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1354 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1355 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001356
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001358 LValueReferenceType *NewIP =
1359 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001360 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 }
1362
John McCall6b304a02009-09-24 23:30:46 +00001363 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001364 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1365 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001366 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001367 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001368
Sebastian Redl7c80bd62009-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 Foad4ba2a172011-01-12 09:06:06 +00001374QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-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 McCall54e14c42009-10-22 22:37:11 +00001378 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-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 McCall54e14c42009-10-22 22:37:11 +00001385 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1386
Sebastian Redl7c80bd62009-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 McCall54e14c42009-10-22 22:37:11 +00001390 if (InnerRef || !T.isCanonical()) {
1391 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1392 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-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 Yasskinc6ed7292010-12-23 01:01:28 +00001397 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001398 }
1399
John McCall6b304a02009-09-24 23:30:46 +00001400 RValueReferenceType *New
1401 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001402 Types.push_back(New);
1403 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 return QualType(New, 0);
1405}
1406
Sebastian Redlf30208a2009-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 Foad4ba2a172011-01-12 09:06:06 +00001409QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-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 Gregor87c12c42009-11-04 16:49:01 +00001423 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-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 Yasskinc6ed7292010-12-23 01:01:28 +00001429 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001430 }
John McCall6b304a02009-09-24 23:30:46 +00001431 MemberPointerType *New
1432 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001433 Types.push_back(New);
1434 MemberPointerTypes.InsertNode(New, InsertPos);
1435 return QualType(New, 0);
1436}
1437
Mike Stump1eb44332009-09-09 15:08:12 +00001438/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001439/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001440QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001441 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001442 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001443 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001444 assert((EltTy->isDependentType() ||
1445 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001446 "Constant array of VLAs is illegal!");
1447
Chris Lattner38aeec72009-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 Foad9f71a8f2010-12-07 08:25:34 +00001451 ArySize =
1452 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001455 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001458 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001459 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001461
John McCall3b657512011-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 Bagnara63e7d252011-01-27 19:55:10 +00001468 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001469 Canon = getQualifiedType(Canon, canonSplit.second);
1470
Reid Spencer5f016e22007-07-11 17:01:13 +00001471 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001472 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001473 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001474 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 }
Mike Stump1eb44332009-09-09 15:08:12 +00001476
John McCall6b304a02009-09-24 23:30:46 +00001477 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001478 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001479 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 Types.push_back(New);
1481 return QualType(New, 0);
1482}
1483
John McCallce889032011-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 Jahanian745da3a2010-09-24 17:30:16 +00001490
John McCallce889032011-01-18 08:40:38 +00001491 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001492
John McCallce889032011-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 Jahanian745da3a2010-09-24 17:30:16 +00001607
Steve Naroffbdbf7b02007-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 Gregor7e7eb3d2009-07-06 15:59:29 +00001610QualType ASTContext::getVariableArrayType(QualType EltTy,
1611 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001612 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001613 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001614 SourceRange Brackets) const {
Eli Friedmanc5773c42008-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 McCall3b657512011-01-19 10:06:00 +00001617 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001618
John McCall3b657512011-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 Bagnara63e7d252011-01-27 19:55:10 +00001623 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001624 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001625 }
1626
John McCall6b304a02009-09-24 23:30:46 +00001627 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001628 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001629
1630 VariableArrayTypes.push_back(New);
1631 Types.push_back(New);
1632 return QualType(New, 0);
1633}
1634
Douglas Gregor898574e2008-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 Gregor04d4bee2009-07-31 00:23:35 +00001637/// type.
John McCall3b657512011-01-19 10:06:00 +00001638QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1639 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001640 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001641 unsigned elementTypeQuals,
1642 SourceRange brackets) const {
1643 assert((!numElements || numElements->isTypeDependent() ||
1644 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001645 "Size must be type- or value-dependent!");
1646
John McCall3b657512011-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 Gregor789b1f62010-02-04 18:10:26 +00001667 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001668 DependentSizedArrayType::Profile(ID, *this,
1669 QualType(canonElementType.first, 0),
1670 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001671
John McCall3b657512011-01-19 10:06:00 +00001672 // Look for an existing type with these properties.
1673 DependentSizedArrayType *canonTy =
1674 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001675
John McCall3b657512011-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 Gregorcb78d882009-11-19 18:03:26 +00001684 }
1685
John McCall3b657512011-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 Stump1eb44332009-09-09 15:08:12 +00001689
John McCall3b657512011-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 Gregor898574e2008-12-05 23:32:09 +00001703}
1704
John McCall3b657512011-01-19 10:06:00 +00001705QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001706 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001707 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001708 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001709 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001710
John McCall3b657512011-01-19 10:06:00 +00001711 void *insertPos = 0;
1712 if (IncompleteArrayType *iat =
1713 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1714 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001715
1716 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-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 Friedmanc5773c42008-02-15 18:16:39 +00001720
John McCall3b657512011-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 Friedmanc5773c42008-02-15 18:16:39 +00001726
1727 // Get the new insert position for the node we care about.
John McCall3b657512011-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 Kremenek2bd24ba2007-10-29 23:37:31 +00001731 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001732
John McCall3b657512011-01-19 10:06:00 +00001733 IncompleteArrayType *newType = new (*this, TypeAlignment)
1734 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001735
John McCall3b657512011-01-19 10:06:00 +00001736 IncompleteArrayTypes.InsertNode(newType, insertPos);
1737 Types.push_back(newType);
1738 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001739}
1740
Steve Naroff73322922007-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 Thompson82287d12010-02-05 00:12:22 +00001743QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001744 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001745 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 // Check if we've already instantiated a vector of this type.
1748 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001749 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001750
Reid Spencer5f016e22007-07-11 17:01:13 +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 Gregor255210e2010-08-06 10:14:59 +00001758 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001759 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 // Get the new insert position for the node we care about.
1762 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001763 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 }
John McCall6b304a02009-09-24 23:30:46 +00001765 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001766 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 VectorTypes.InsertNode(New, InsertPos);
1768 Types.push_back(New);
1769 return QualType(New, 0);
1770}
1771
Nate Begeman213541a2008-04-18 23:10:10 +00001772/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001773/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001774QualType
1775ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall3b657512011-01-19 10:06:00 +00001776 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Steve Naroff73322922007-07-18 18:00:27 +00001778 // Check if we've already instantiated a vector of this type.
1779 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001780 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001781 VectorType::GenericVector);
Steve Naroff73322922007-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 McCall467b27b2009-10-22 20:10:53 +00001789 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001790 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Steve Naroff73322922007-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 Yasskinc6ed7292010-12-23 01:01:28 +00001794 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001795 }
John McCall6b304a02009-09-24 23:30:46 +00001796 ExtVectorType *New = new (*this, TypeAlignment)
1797 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001798 VectorTypes.InsertNode(New, InsertPos);
1799 Types.push_back(New);
1800 return QualType(New, 0);
1801}
1802
Jay Foad4ba2a172011-01-12 09:06:06 +00001803QualType
1804ASTContext::getDependentSizedExtVectorType(QualType vecType,
1805 Expr *SizeExpr,
1806 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001807 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001808 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001809 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Douglas Gregor2ec09f12009-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 McCall6b304a02009-09-24 23:30:46 +00001818 New = new (*this, TypeAlignment)
1819 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1820 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001821 } else {
1822 QualType CanonVecTy = getCanonicalType(vecType);
1823 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001824 New = new (*this, TypeAlignment)
1825 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1826 AttrLoc);
Douglas Gregor789b1f62010-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 Gregor2ec09f12009-07-31 03:54:25 +00001832 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1833 } else {
1834 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1835 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001836 New = new (*this, TypeAlignment)
1837 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001838 }
1839 }
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001841 Types.push_back(New);
1842 return QualType(New, 0);
1843}
1844
Douglas Gregor72564e72009-02-26 23:50:07 +00001845/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001846///
Jay Foad4ba2a172011-01-12 09:06:06 +00001847QualType
1848ASTContext::getFunctionNoProtoType(QualType ResultTy,
1849 const FunctionType::ExtInfo &Info) const {
Rafael Espindola264ba482010-03-30 20:24:48 +00001850 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001851 // Unique functions, to guarantee there is only one function of a particular
1852 // structure.
1853 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001854 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001857 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001858 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001859 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001862 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001863 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001864 Canonical =
1865 getFunctionNoProtoType(getCanonicalType(ResultTy),
1866 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001869 FunctionNoProtoType *NewIP =
1870 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001871 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001872 }
Mike Stump1eb44332009-09-09 15:08:12 +00001873
John McCall6b304a02009-09-24 23:30:46 +00001874 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001875 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001877 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001878 return QualType(New, 0);
1879}
1880
1881/// getFunctionType - Return a normal function type with a typed argument
1882/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001883QualType
1884ASTContext::getFunctionType(QualType ResultTy,
1885 const QualType *ArgArray, unsigned NumArgs,
1886 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001887 // Unique functions, to guarantee there is only one function of a particular
1888 // structure.
1889 llvm::FoldingSetNodeID ID;
John McCalle23cf432010-12-14 08:05:40 +00001890 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001891
1892 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001893 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001894 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001895 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001896
1897 // Determine whether the type being created is already canonical or not.
John McCalle23cf432010-12-14 08:05:40 +00001898 bool isCanonical = !EPI.HasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001900 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 isCanonical = false;
1902
John McCalle23cf432010-12-14 08:05:40 +00001903 const CallingConv CallConv = EPI.ExtInfo.getCC();
1904
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001906 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001907 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001908 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 llvm::SmallVector<QualType, 16> CanonicalArgs;
1910 CanonicalArgs.reserve(NumArgs);
1911 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001912 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001913
John McCalle23cf432010-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 Lattnerf52ab252008-04-06 22:59:24 +00001923 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001924 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00001925 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00001926
Reid Spencer5f016e22007-07-11 17:01:13 +00001927 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001928 FunctionProtoType *NewIP =
1929 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001930 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001932
Douglas Gregor72564e72009-02-26 23:50:07 +00001933 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001934 // for two variable size arrays (for parameter and exception types) at the
1935 // end of them.
John McCalle23cf432010-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);
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001942 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 return QualType(FTP, 0);
1944}
1945
John McCall3cb0ebd2010-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 Foad4ba2a172011-01-12 09:06:06 +00001962 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00001963 assert(NeedsInjectedClassNameType(Decl));
1964 if (Decl->TypeForDecl) {
1965 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00001966 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-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 McCallf4c73712011-01-19 06:33:43 +00001971 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00001972 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00001973 Decl->TypeForDecl = newType;
1974 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00001975 }
1976 return QualType(Decl->TypeForDecl, 0);
1977}
1978
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001979/// getTypeDeclType - Return the unique reference to the type for the
1980/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00001981QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001982 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001983 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001984
John McCall19c85762010-02-16 03:57:14 +00001985 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001986 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001987
John McCallbecb8d52010-03-10 06:48:02 +00001988 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1989 "Template type parameter types are always available.");
1990
John McCall19c85762010-02-16 03:57:14 +00001991 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001992 assert(!Record->getPreviousDeclaration() &&
1993 "struct/union has previous declaration");
1994 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001995 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001996 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001997 assert(!Enum->getPreviousDeclaration() &&
1998 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00001999 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002000 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002001 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002002 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2003 Decl->TypeForDecl = newType;
2004 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002005 } else
John McCallbecb8d52010-03-10 06:48:02 +00002006 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002007
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002008 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002009}
2010
Reid Spencer5f016e22007-07-11 17:01:13 +00002011/// getTypedefType - Return the unique reference to the type for the
2012/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002013QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002014ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002017 if (Canonical.isNull())
2018 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002019 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002020 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002021 Decl->TypeForDecl = newType;
2022 Types.push_back(newType);
2023 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002024}
2025
Jay Foad4ba2a172011-01-12 09:06:06 +00002026QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-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 McCallf4c73712011-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 Kyrtzidis400f5122010-07-04 21:44:47 +00002037}
2038
Jay Foad4ba2a172011-01-12 09:06:06 +00002039QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-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 McCallf4c73712011-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 Kyrtzidis400f5122010-07-04 21:44:47 +00002050}
2051
John McCall9d156a72011-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 McCall49a832b2009-10-18 09:09:24 +00002073/// \brief Retrieve a substitution-result type.
2074QualType
2075ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002076 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002077 assert(Replacement.isCanonical()
John McCall49a832b2009-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 Gregorc3069d62011-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 Gregorfab9d672009-02-05 23:33:38 +00002132/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002133/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002134/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002135QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002136 bool ParameterPack,
Jay Foad4ba2a172011-01-12 09:06:06 +00002137 IdentifierInfo *Name) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002138 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00002139 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002140 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002141 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002142 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2143
2144 if (TypeParm)
2145 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Douglas Gregorefed5c82010-06-16 15:23:05 +00002147 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002148 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00002149 TypeParm = new (*this, TypeAlignment)
2150 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-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 Carlsson76e4ce42009-06-16 00:30:48 +00002156 } else
John McCall6b304a02009-09-24 23:30:46 +00002157 TypeParm = new (*this, TypeAlignment)
2158 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-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 McCall3cb0ebd2010-03-10 03:28:59 +00002166TypeSourceInfo *
2167ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2168 SourceLocation NameLoc,
2169 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002170 QualType CanonType) const {
John McCall3cb0ebd2010-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 Stump1eb44332009-09-09 15:08:12 +00002184QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002185ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002186 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002187 QualType Canon) const {
John McCalld5532b62009-11-23 01:53:49 +00002188 unsigned NumArgs = Args.size();
2189
John McCall833ca992009-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 McCall31f17ec2010-04-27 00:57:59 +00002195 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00002196 Canon);
John McCall833ca992009-10-29 08:12:44 +00002197}
2198
2199QualType
2200ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002201 const TemplateArgument *Args,
2202 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002203 QualType Canon) const {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002204 if (!Canon.isNull())
2205 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002206 else
2207 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00002208
Douglas Gregor1275ae02009-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 Stump1eb44332009-09-09 15:08:12 +00002212 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00002213 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002214 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002215 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002216 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002217 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002218 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Douglas Gregor55f6b142009-02-09 18:46:07 +00002220 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002221 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002222}
2223
Mike Stump1eb44332009-09-09 15:08:12 +00002224QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002225ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2226 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002227 unsigned NumArgs) const {
Argyrios Kyrtzidis9763e222010-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 Bagnara465d41b2010-05-11 21:36:43 +00002263ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2264 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002265 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002266 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002267 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002268
2269 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002270 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002271 if (T)
2272 return QualType(T, 0);
2273
Douglas Gregor789b1f62010-02-04 18:10:26 +00002274 QualType Canon = NamedType;
2275 if (!Canon.isCanonical()) {
2276 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002277 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2278 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002279 (void)CheckT;
2280 }
2281
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002282 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002283 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002284 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002285 return QualType(T, 0);
2286}
2287
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002288QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002289ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-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 Gregor4a2023f2010-03-31 20:19:30 +00002312QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2313 NestedNameSpecifier *NNS,
2314 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002315 QualType Canon) const {
Douglas Gregord57959a2009-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 Gregor4a2023f2010-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 Gregord57959a2009-03-27 23:10:48 +00002326 }
2327
2328 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002329 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002330
2331 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002332 DependentNameType *T
2333 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002334 if (T)
2335 return QualType(T, 0);
2336
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002337 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002338 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002339 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002340 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002341}
2342
Mike Stump1eb44332009-09-09 15:08:12 +00002343QualType
John McCall33500952010-06-11 00:33:02 +00002344ASTContext::getDependentTemplateSpecializationType(
2345 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002346 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002347 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002348 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-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 Foad4ba2a172011-01-12 09:06:06 +00002364 const TemplateArgument *Args) const {
Douglas Gregor17343172009-04-01 00:28:59 +00002365 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2366
Douglas Gregor789b1f62010-02-04 18:10:26 +00002367 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002368 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2369 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002370
2371 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002372 DependentTemplateSpecializationType *T
2373 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002374 if (T)
2375 return QualType(T, 0);
2376
John McCall33500952010-06-11 00:33:02 +00002377 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002378
John McCall33500952010-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 Gregor17343172009-04-01 00:28:59 +00002388 }
2389
John McCall33500952010-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 McCallef990012010-06-11 11:07:21 +00002403 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002404 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002405 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002406 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002407 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002408}
2409
Douglas Gregorcded4f62011-01-14 17:04:44 +00002410QualType ASTContext::getPackExpansionType(QualType Pattern,
2411 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002412 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002413 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-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 Gregorcded4f62011-01-14 17:04:44 +00002425 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002426
2427 // Find the insert position again.
2428 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2429 }
2430
Douglas Gregorcded4f62011-01-14 17:04:44 +00002431 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002432 Types.push_back(T);
2433 PackExpansionTypes.InsertNode(T, InsertPos);
2434 return QualType(T, 0);
2435}
2436
Chris Lattner88cb27a2008-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 Gregor2e1cd422008-11-17 14:58:09 +00002441 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002442}
2443
John McCallc12c5bb2010-05-15 11:32:37 +00002444static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-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 Lattner88cb27a2008-04-07 04:56:42 +00002455 unsigned &NumProtocols) {
2456 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002457
Chris Lattner88cb27a2008-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 McCallc12c5bb2010-05-15 11:32:37 +00002466QualType ASTContext::getObjCObjectType(QualType BaseType,
2467 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002468 unsigned NumProtocols) const {
John McCallc12c5bb2010-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 Naroffd1b3c2d2009-06-17 22:40:22 +00002475 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002476 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002477 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002478 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2479 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002480
John McCallc12c5bb2010-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 McCall54e14c42009-10-22 22:37:11 +00002483 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002484 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2485 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2486 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002487 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2488 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002489 unsigned UniqueCount = NumProtocols;
2490
John McCall54e14c42009-10-22 22:37:11 +00002491 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002492 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2493 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002494 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002495 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2496 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002497 }
2498
2499 // Regenerate InsertPos.
John McCallc12c5bb2010-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 Foad4ba2a172011-01-12 09:06:06 +00002516QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-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 McCall54e14c42009-10-22 22:37:11 +00002531 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2532 }
2533
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002534 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002535 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2536 ObjCObjectPointerType *QType =
2537 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002538
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002539 Types.push_back(QType);
2540 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002541 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002542}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002543
Douglas Gregordeacbdc2010-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 Foad4ba2a172011-01-12 09:06:06 +00002546QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002547 if (Decl->TypeForDecl)
2548 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002549
Douglas Gregordeacbdc2010-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 Jahanian4b6c9052007-10-11 00:55:41 +00002556}
2557
Douglas Gregor72564e72009-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 Naroff9752f252007-08-01 18:02:17 +00002560/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002561/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002562/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002563QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002564 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002565 if (tofExpr->isTypeDependent()) {
2566 llvm::FoldingSetNodeID ID;
2567 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002568
Douglas Gregorb1975722009-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 McCall6b304a02009-09-24 23:30:46 +00002575 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002576 QualType((TypeOfExprType*)Canon, 0));
2577 }
2578 else {
2579 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002580 Canon
2581 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002582 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2583 toe = Canon;
2584 }
2585 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002586 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002587 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002588 }
Steve Naroff9752f252007-08-01 18:02:17 +00002589 Types.push_back(toe);
2590 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002591}
2592
Steve Naroff9752f252007-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 Stump1eb44332009-09-09 15:08:12 +00002596/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002597/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002598QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002599 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002600 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002601 Types.push_back(tot);
2602 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002603}
2604
Anders Carlsson60a9a2a2009-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 Foad4ba2a172011-01-12 09:06:06 +00002607static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002608 if (e->isTypeDependent())
2609 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Anders Carlsson60a9a2a2009-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 Stump1eb44332009-09-09 15:08:12 +00002626
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002627 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002628
2629 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002630 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002631 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002632 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002633
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002634 return T;
2635}
2636
Anders Carlsson395b4752009-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 Stump1eb44332009-09-09 15:08:12 +00002640/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002641/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002642QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002643 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002644 if (e->isTypeDependent()) {
2645 llvm::FoldingSetNodeID ID;
2646 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002647
Douglas Gregor9d702ae2009-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 McCall6b304a02009-09-24 23:30:46 +00002654 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002655 QualType((DecltypeType*)Canon, 0));
2656 }
2657 else {
2658 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002659 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002660 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2661 dt = Canon;
2662 }
2663 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002664 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002665 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002666 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002667 Types.push_back(dt);
2668 return QualType(dt, 0);
2669}
2670
Reid Spencer5f016e22007-07-11 17:01:13 +00002671/// getTagDeclType - Return the unique reference to the type for the
2672/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002673QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002674 assert (Decl);
Mike Stumpe607ed02009-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));
Reid Spencer5f016e22007-07-11 17:01:13 +00002678}
2679
Mike Stump1eb44332009-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 Carlssona3ccda52009-12-12 00:26:23 +00002683CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002684 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002685}
2686
Argyrios Kyrtzidis64c438a2008-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 Lattner8b9023b2007-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 Gregorb4e66d52008-11-03 14:12:49 +00002704 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002705}
2706
Chris Lattnere6327742008-04-02 05:18:44 +00002707//===----------------------------------------------------------------------===//
2708// Type Operators
2709//===----------------------------------------------------------------------===//
2710
Jay Foad4ba2a172011-01-12 09:06:06 +00002711CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002712 // Push qualifiers into arrays, and then discard any remaining
2713 // qualifiers.
2714 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002715 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002716 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-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 Lattnerc63a1f22008-08-04 07:31:14 +00002729
John McCall62c28c82011-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 Gregor9dadd942010-05-17 18:45:21 +00002742 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002743 quals = splitType.second;
2744 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002745 }
2746
John McCall62c28c82011-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 Carruth28e318c2009-12-29 07:16:59 +00002762
Douglas Gregor9dadd942010-05-17 18:45:21 +00002763 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002764 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002765 CAT->getSizeModifier(), 0);
2766 }
2767
Douglas Gregor9dadd942010-05-17 18:45:21 +00002768 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002769 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002770 }
2771
Douglas Gregor9dadd942010-05-17 18:45:21 +00002772 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002773 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002774 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002775 VAT->getSizeModifier(),
2776 VAT->getIndexTypeCVRQualifiers(),
2777 VAT->getBracketsRange());
2778 }
2779
2780 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002781 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002782 DSAT->getSizeModifier(), 0,
2783 SourceRange());
2784}
2785
Douglas Gregor5a57efd2010-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 Foad4ba2a172011-01-12 09:06:06 +00002828DeclarationNameInfo
2829ASTContext::getNameForTemplate(TemplateName Name,
2830 SourceLocation NameLoc) const {
John McCall80ad16f2009-11-24 18:42:40 +00002831 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002832 // DNInfo work in progress: CHECKME: what about DNLoc?
2833 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2834
John McCall80ad16f2009-11-24 18:42:40 +00002835 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002836 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002837 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002838 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2839 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002840 } else {
Abramo Bagnara25777432010-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 McCall80ad16f2009-11-24 18:42:40 +00002847 }
2848 }
2849
John McCall0bd6feb2009-12-02 08:04:21 +00002850 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2851 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002852 // DNInfo work in progress: CHECKME: what about DNLoc?
2853 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002854}
2855
Jay Foad4ba2a172011-01-12 09:06:06 +00002856TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor3e1274f2010-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 Kyrtzidis97fbaa22009-07-18 00:34:25 +00002863 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002864 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002865
Douglas Gregor1aee05d2011-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 McCall0bd6feb2009-12-02 08:04:21 +00002875 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002876
Douglas Gregor25a3ef72009-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 Gregordb0d4b72009-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 Stump1eb44332009-09-09 15:08:12 +00002888TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00002889ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00002890 switch (Arg.getKind()) {
2891 case TemplateArgument::Null:
2892 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002893
Douglas Gregor1275ae02009-07-28 23:00:59 +00002894 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002895 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002896
Douglas Gregor1275ae02009-07-28 23:00:59 +00002897 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002898 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002899
Douglas Gregor788cd062009-11-11 01:00:40 +00002900 case TemplateArgument::Template:
2901 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00002902
2903 case TemplateArgument::TemplateExpansion:
2904 return TemplateArgument(getCanonicalTemplateName(
2905 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00002906 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00002907
Douglas Gregor1275ae02009-07-28 23:00:59 +00002908 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002909 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002910 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002911
Douglas Gregor1275ae02009-07-28 23:00:59 +00002912 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002913 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002914
Douglas Gregor1275ae02009-07-28 23:00:59 +00002915 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00002916 if (Arg.pack_size() == 0)
2917 return Arg;
2918
Douglas Gregor910f8002010-11-07 23:05:16 +00002919 TemplateArgument *CanonArgs
2920 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00002921 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002922 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002923 AEnd = Arg.pack_end();
2924 A != AEnd; (void)++A, ++Idx)
2925 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002926
Douglas Gregor910f8002010-11-07 23:05:16 +00002927 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-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 Gregord57959a2009-03-27 23:10:48 +00002936NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00002937ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00002938 if (!NNS)
Douglas Gregord57959a2009-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 Stump1eb44332009-09-09 15:08:12 +00002944 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-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 Gregor264bf662010-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 Gregor643f8432010-11-04 00:14:23 +00002971 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-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 McCall3b657512011-01-19 10:06:00 +00002983 return NestedNameSpecifier::Create(*this, 0, false,
2984 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-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 Lattnerc63a1f22008-08-04 07:31:14 +00002996
Jay Foad4ba2a172011-01-12 09:06:06 +00002997const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002998 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002999 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-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 Stump1eb44332009-09-09 15:08:12 +00003004
John McCall0953e762009-09-24 19:53:00 +00003005 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003006 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003007 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003008
John McCall0953e762009-09-24 19:53:00 +00003009 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-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 Stump1eb44332009-09-09 15:08:12 +00003012
Chris Lattnerc63a1f22008-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 Gregor50d62d12009-08-05 05:36:45 +00003015 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003016
John McCall3b657512011-01-19 10:06:00 +00003017 SplitQualType split = T.getSplitDesugaredType();
3018 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003019
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003020 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003021 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3022 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003023 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003024
Chris Lattnerc63a1f22008-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 McCall3b657512011-01-19 10:06:00 +00003027 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Chris Lattnerc63a1f22008-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 McCall0953e762009-09-24 19:53:00 +00003032 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003033 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3034 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3035 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003036 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003037
Mike Stump1eb44332009-09-09 15:08:12 +00003038 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003039 = dyn_cast<DependentSizedArrayType>(ATy))
3040 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003041 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003042 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003043 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003044 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003045 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003046
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003047 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003048 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003049 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003050 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003051 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003052 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003053}
3054
Chris Lattnere6327742008-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 Foad4ba2a172011-01-12 09:06:06 +00003061QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-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 Stump1eb44332009-09-09 15:08:12 +00003068
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003069 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003070
3071 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003072 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003073}
3074
John McCall3b657512011-01-19 10:06:00 +00003075QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3076 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003077}
3078
John McCall3b657512011-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 Stump1eb44332009-09-09 15:08:12 +00003085
John McCall3b657512011-01-19 10:06:00 +00003086 type = array->getElementType();
3087 qs.addConsistentQualifiers(split.second);
3088 }
Mike Stump1eb44332009-09-09 15:08:12 +00003089
John McCall3b657512011-01-19 10:06:00 +00003090 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003091}
3092
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003093/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003094uint64_t
Fariborz Jahanian0de78992009-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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnera75cea32008-04-06 23:38:49 +00003106static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003107 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003108 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003109
John McCall183700f2009-09-21 23:43:11 +00003110 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3111 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003112 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003113 case BuiltinType::Float: return FloatRank;
3114 case BuiltinType::Double: return DoubleRank;
3115 case BuiltinType::LongDouble: return LongDoubleRank;
3116 }
3117}
3118
Mike Stump1eb44332009-09-09 15:08:12 +00003119/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3120/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-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 Lattner1361b112008-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 Naroff716c7302007-08-27 01:41:48 +00003128 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003129 case FloatRank: return FloatComplexTy;
3130 case DoubleRank: return DoubleComplexTy;
3131 case LongDoubleRank: return LongDoubleComplexTy;
3132 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003133 }
Chris Lattner1361b112008-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 Narofff1448a02007-08-27 01:27:54 +00003141 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003142}
3143
Chris Lattner7cfeb082008-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 Stump1eb44332009-09-09 15:08:12 +00003147/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003148int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003149 FloatingRank LHSR = getFloatingRank(LHS);
3150 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003151
Chris Lattnera75cea32008-04-06 23:38:49 +00003152 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003153 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003154 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003155 return 1;
3156 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003157}
3158
Chris Lattnerf52ab252008-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 McCallf4c73712011-01-19 06:33:43 +00003162unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003163 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003164 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003165 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003166
Chris Lattner3f59c972010-12-25 23:25:43 +00003167 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3168 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003169 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3170
Alisdair Meredithf5c209d2009-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 Lattnerf52ab252008-04-06 22:59:24 +00003177 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003178 default: assert(0 && "getIntegerRank(): not a built-in integer");
3179 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003180 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003181 case BuiltinType::Char_S:
3182 case BuiltinType::Char_U:
3183 case BuiltinType::SChar:
3184 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003185 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003186 case BuiltinType::Short:
3187 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003188 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003189 case BuiltinType::Int:
3190 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003191 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003192 case BuiltinType::Long:
3193 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003194 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003195 case BuiltinType::LongLong:
3196 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003197 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003198 case BuiltinType::Int128:
3199 case BuiltinType::UInt128:
3200 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003201 }
3202}
3203
Eli Friedman04e83572009-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 Foad4ba2a172011-01-12 09:06:06 +00003209QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003210 if (E->isTypeDependent() || E->isValueDependent())
3211 return QualType();
3212
Eli Friedman04e83572009-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 Friedmana95d7572009-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 Foad4ba2a172011-01-12 09:06:06 +00003241QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003242 assert(!Promotable.isNull());
3243 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003244 if (const EnumType *ET = Promotable->getAs<EnumType>())
3245 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-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 Stump1eb44332009-09-09 15:08:12 +00003254/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003255/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003256/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003257int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003258 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3259 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003260 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003261
Chris Lattnerf52ab252008-04-06 22:59:24 +00003262 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3263 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Chris Lattner7cfeb082008-04-06 23:55:33 +00003265 unsigned LHSRank = getIntegerRank(LHSC);
3266 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003267
Chris Lattner7cfeb082008-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 Stump1eb44332009-09-09 15:08:12 +00003272
Chris Lattner7cfeb082008-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 Stump1eb44332009-09-09 15:08:12 +00003278
Chris Lattner7cfeb082008-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 Stump1eb44332009-09-09 15:08:12 +00003281 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003282 return -1;
3283 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003284
Chris Lattner7cfeb082008-04-06 23:55:33 +00003285 // If the unsigned [RHS] type is larger, return it.
3286 if (RHSRank >= LHSRank)
3287 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003288
Chris Lattner7cfeb082008-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 Stump1eb44332009-09-09 15:08:12 +00003291 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003292 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003293}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003294
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003295static RecordDecl *
Jay Foad4ba2a172011-01-12 09:06:06 +00003296CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
Anders Carlsson79cbc7d2009-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 Stump1eb44332009-09-09 15:08:12 +00003304// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003305QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003306 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003307 CFConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003308 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003309 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003310 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003311
Anders Carlssonf06273f2007-11-19 00:25:30 +00003312 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Anders Carlsson71993dd2007-08-17 05:31:46 +00003314 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003315 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003316 // int flags;
3317 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003318 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003319 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003320 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003321 FieldTypes[3] = LongTy;
3322
Anders Carlsson71993dd2007-08-17 05:31:46 +00003323 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003324 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003325 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003326 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003327 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003328 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003329 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003330 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003331 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003332 }
3333
Douglas Gregor838db382010-02-11 01:19:42 +00003334 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003335 }
Mike Stump1eb44332009-09-09 15:08:12 +00003336
Anders Carlsson71993dd2007-08-17 05:31:46 +00003337 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003338}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003339
Douglas Gregor319ac892009-04-23 22:29:11 +00003340void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003341 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003342 assert(Rec && "Invalid CFConstantStringType");
3343 CFConstantStringTypeDecl = Rec->getDecl();
3344}
3345
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003346// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003347QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003348 if (!NSConstantStringTypeDecl) {
3349 NSConstantStringTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003350 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Fariborz Jahanian2bb5dda2010-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 McCall2888b652010-04-30 21:35:41 +00003370 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-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 Foad4ba2a172011-01-12 09:06:06 +00003386QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003387 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003388 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003389 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003390 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003391 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003392
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003393 QualType FieldTypes[] = {
3394 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003395 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003396 getPointerType(UnsignedLongTy),
3397 getConstantArrayType(UnsignedLongTy,
3398 llvm::APInt(32, 5), ArrayType::Normal, 0)
3399 };
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Douglas Gregor44b43212008-12-11 16:49:14 +00003401 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003402 FieldDecl *Field = FieldDecl::Create(*this,
3403 ObjCFastEnumerationStateTypeDecl,
3404 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003405 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003406 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003407 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003408 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003409 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003410 }
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Douglas Gregor838db382010-02-11 01:19:42 +00003412 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003413 }
Mike Stump1eb44332009-09-09 15:08:12 +00003414
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003415 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3416}
3417
Jay Foad4ba2a172011-01-12 09:06:06 +00003418QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003419 if (BlockDescriptorType)
3420 return getTagDeclType(BlockDescriptorType);
3421
3422 RecordDecl *T;
3423 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003424 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003425 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003426 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003427
3428 QualType FieldTypes[] = {
3429 UnsignedLongTy,
3430 UnsignedLongTy,
3431 };
3432
3433 const char *FieldNames[] = {
3434 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003435 "Size"
Mike Stumpadaaad32009-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 McCalla93c9342009-12-07 02:54:59 +00003443 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003444 /*BitWidth=*/0,
3445 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003446 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003447 T->addDecl(Field);
3448 }
3449
Douglas Gregor838db382010-02-11 01:19:42 +00003450 T->completeDefinition();
Mike Stumpadaaad32009-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 Foad4ba2a172011-01-12 09:06:06 +00003463QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003464 if (BlockDescriptorExtendedType)
3465 return getTagDeclType(BlockDescriptorExtendedType);
3466
3467 RecordDecl *T;
3468 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003469 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003470 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003471 T->startDefinition();
Mike Stump083c25e2009-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 McCalla93c9342009-12-07 02:54:59 +00003492 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003493 /*BitWidth=*/0,
3494 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003495 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003496 T->addDecl(Field);
3497 }
3498
Douglas Gregor838db382010-02-11 01:19:42 +00003499 T->completeDefinition();
Mike Stump083c25e2009-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 Foad4ba2a172011-01-12 09:06:06 +00003512bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stumpaf7b44d2009-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 Jahaniane38be612010-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 Stumpaf7b44d2009-10-21 18:16:27 +00003526 return false;
3527}
3528
Jay Foad4ba2a172011-01-12 09:06:06 +00003529QualType
3530ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003531 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003532 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003533 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003534 // unsigned int __flags;
3535 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003536 // void *__copy_helper; // as needed
3537 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003538 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003539 // } *
3540
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003541 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3542
3543 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003544 llvm::SmallString<36> Name;
3545 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3546 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003547 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003548 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003549 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-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 Dunbar4087f272010-08-17 22:39:59 +00003563 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-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 McCalla93c9342009-12-07 02:54:59 +00003578 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003579 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003580 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003581 T->addDecl(Field);
3582 }
3583
Douglas Gregor838db382010-02-11 01:19:42 +00003584 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003585
3586 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003587}
3588
3589
3590QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003591 bool BlockHasCopyDispose,
Jay Foad4ba2a172011-01-12 09:06:06 +00003592 llvm::SmallVectorImpl<const Expr *> &Layout) const {
John McCallea1471e2010-05-20 01:18:31 +00003593
Mike Stumpadaaad32009-10-20 02:12:22 +00003594 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003595 llvm::SmallString<36> Name;
3596 llvm::raw_svector_ostream(Name) << "__block_literal_"
3597 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003598 RecordDecl *T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003599 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003600 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003601 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003602 QualType FieldTypes[] = {
3603 getPointerType(VoidPtrTy),
3604 IntTy,
3605 IntTy,
3606 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003607 (BlockHasCopyDispose ?
3608 getPointerType(getBlockDescriptorExtendedType()) :
3609 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-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 Stumpea26cb52009-10-21 03:49:08 +00003621 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003622 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003623 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003624 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003625 Field->setAccess(AS_public);
Mike Stumpea26cb52009-10-21 03:49:08 +00003626 T->addDecl(Field);
3627 }
3628
John McCallea1471e2010-05-20 01:18:31 +00003629 for (unsigned i = 0; i < Layout.size(); ++i) {
3630 const Expr *E = Layout[i];
Mike Stumpea26cb52009-10-21 03:49:08 +00003631
John McCallea1471e2010-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 Dunbar4087f272010-08-17 22:39:59 +00003640 FieldType = BuildByRefType(D->getName(), FieldType);
John McCallea1471e2010-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 Stumpea26cb52009-10-21 03:49:08 +00003648
3649 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCallea1471e2010-05-20 01:18:31 +00003650 FieldName, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003651 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003652 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003653 T->addDecl(Field);
3654 }
3655
Douglas Gregor838db382010-02-11 01:19:42 +00003656 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003657
3658 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003659}
3660
Douglas Gregor319ac892009-04-23 22:29:11 +00003661void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003662 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003663 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3664 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3665}
3666
Anders Carlssone8c49532007-10-29 06:33:42 +00003667// This returns true if a type has been typedefed to BOOL:
3668// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003669static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003670 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003671 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3672 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003674 return false;
3675}
3676
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003677/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003678/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003679CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck199c3d62010-01-11 17:06:35 +00003680 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003681
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003682 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003683 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003684 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003685 // Treat arrays as pointers, since that's how they're passed in.
3686 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003687 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003688 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003689}
3690
3691static inline
3692std::string charUnitsToString(const CharUnits &CU) {
3693 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003694}
3695
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003696/// getObjCEncodingForBlockDecl - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003697/// declaration.
3698void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
Jay Foad4ba2a172011-01-12 09:06:06 +00003699 std::string& S) const {
David Chisnall5e530af2009-11-17 19:33:30 +00003700 const BlockDecl *Decl = Expr->getBlockDecl();
3701 QualType BlockTy =
3702 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3703 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003704 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003705 // Compute size of all parameters.
3706 // Start with computing size of a pointer in number of bytes.
3707 // FIXME: There might(should) be a better way of doing this computation!
3708 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003709 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3710 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003711 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003712 E = Decl->param_end(); PI != E; ++PI) {
3713 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003714 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003715 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003716 ParmOffset += sz;
3717 }
3718 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003719 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003720 // Block pointer and offset.
3721 S += "@?0";
3722 ParmOffset = PtrSize;
3723
3724 // Argument types.
3725 ParmOffset = PtrSize;
3726 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3727 Decl->param_end(); PI != E; ++PI) {
3728 ParmVarDecl *PVDecl = *PI;
3729 QualType PType = PVDecl->getOriginalType();
3730 if (const ArrayType *AT =
3731 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3732 // Use array's original type only if it has known number of
3733 // elements.
3734 if (!isa<ConstantArrayType>(AT))
3735 PType = PVDecl->getType();
3736 } else if (PType->isFunctionType())
3737 PType = PVDecl->getType();
3738 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003739 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003740 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003741 }
3742}
3743
David Chisnall5389f482010-12-30 14:05:53 +00003744void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3745 std::string& S) {
3746 // Encode result type.
3747 getObjCEncodingForType(Decl->getResultType(), S);
3748 CharUnits ParmOffset;
3749 // Compute size of all parameters.
3750 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3751 E = Decl->param_end(); PI != E; ++PI) {
3752 QualType PType = (*PI)->getType();
3753 CharUnits sz = getObjCEncodingTypeSize(PType);
3754 assert (sz.isPositive() &&
3755 "getObjCEncodingForMethodDecl - Incomplete param type");
3756 ParmOffset += sz;
3757 }
3758 S += charUnitsToString(ParmOffset);
3759 ParmOffset = CharUnits::Zero();
3760
3761 // Argument types.
3762 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3763 E = Decl->param_end(); PI != E; ++PI) {
3764 ParmVarDecl *PVDecl = *PI;
3765 QualType PType = PVDecl->getOriginalType();
3766 if (const ArrayType *AT =
3767 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3768 // Use array's original type only if it has known number of
3769 // elements.
3770 if (!isa<ConstantArrayType>(AT))
3771 PType = PVDecl->getType();
3772 } else if (PType->isFunctionType())
3773 PType = PVDecl->getType();
3774 getObjCEncodingForType(PType, S);
3775 S += charUnitsToString(ParmOffset);
3776 ParmOffset += getObjCEncodingTypeSize(PType);
3777 }
3778}
3779
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003780/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003781/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003782void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003783 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003784 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003785 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003786 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003787 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003788 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003789 // Compute size of all parameters.
3790 // Start with computing size of a pointer in number of bytes.
3791 // FIXME: There might(should) be a better way of doing this computation!
3792 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003793 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003794 // The first two arguments (self and _cmd) are pointers; account for
3795 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003796 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003797 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003798 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003799 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003800 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003801 assert (sz.isPositive() &&
3802 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003803 ParmOffset += sz;
3804 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003805 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003806 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003807 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003808
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003809 // Argument types.
3810 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003811 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003812 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003813 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003814 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003815 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003816 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3817 // Use array's original type only if it has known number of
3818 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003819 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003820 PType = PVDecl->getType();
3821 } else if (PType->isFunctionType())
3822 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003823 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003824 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003825 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003826 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003827 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003828 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003829 }
3830}
3831
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003832/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003833/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003834/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3835/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003836/// Property attributes are stored as a comma-delimited C string. The simple
3837/// attributes readonly and bycopy are encoded as single characters. The
3838/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3839/// encoded as single characters, followed by an identifier. Property types
3840/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003841/// these attributes are defined by the following enumeration:
3842/// @code
3843/// enum PropertyAttributes {
3844/// kPropertyReadOnly = 'R', // property is read-only.
3845/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3846/// kPropertyByref = '&', // property is a reference to the value last assigned
3847/// kPropertyDynamic = 'D', // property is dynamic
3848/// kPropertyGetter = 'G', // followed by getter selector name
3849/// kPropertySetter = 'S', // followed by setter selector name
3850/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3851/// kPropertyType = 't' // followed by old-style type encoding.
3852/// kPropertyWeak = 'W' // 'weak' property
3853/// kPropertyStrong = 'P' // property GC'able
3854/// kPropertyNonAtomic = 'N' // property non-atomic
3855/// };
3856/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003857void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003858 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00003859 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003860 // Collect information from the property implementation decl(s).
3861 bool Dynamic = false;
3862 ObjCPropertyImplDecl *SynthesizePID = 0;
3863
3864 // FIXME: Duplicated code due to poor abstraction.
3865 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003866 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003867 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3868 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003869 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003870 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003871 ObjCPropertyImplDecl *PID = *i;
3872 if (PID->getPropertyDecl() == PD) {
3873 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3874 Dynamic = true;
3875 } else {
3876 SynthesizePID = PID;
3877 }
3878 }
3879 }
3880 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003881 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003882 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003883 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003884 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003885 ObjCPropertyImplDecl *PID = *i;
3886 if (PID->getPropertyDecl() == PD) {
3887 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3888 Dynamic = true;
3889 } else {
3890 SynthesizePID = PID;
3891 }
3892 }
Mike Stump1eb44332009-09-09 15:08:12 +00003893 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003894 }
3895 }
3896
3897 // FIXME: This is not very efficient.
3898 S = "T";
3899
3900 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003901 // GCC has some special rules regarding encoding of properties which
3902 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003903 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003904 true /* outermost type */,
3905 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003906
3907 if (PD->isReadOnly()) {
3908 S += ",R";
3909 } else {
3910 switch (PD->getSetterKind()) {
3911 case ObjCPropertyDecl::Assign: break;
3912 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003913 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003914 }
3915 }
3916
3917 // It really isn't clear at all what this means, since properties
3918 // are "dynamic by default".
3919 if (Dynamic)
3920 S += ",D";
3921
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003922 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3923 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003924
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003925 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3926 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003927 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003928 }
3929
3930 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3931 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003932 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003933 }
3934
3935 if (SynthesizePID) {
3936 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3937 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003938 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003939 }
3940
3941 // FIXME: OBJCGC: weak & strong
3942}
3943
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003944/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003945/// Another legacy compatibility encoding: 32-bit longs are encoded as
3946/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003947/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3948///
3949void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003950 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003951 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00003952 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003953 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003954 else
Jay Foad4ba2a172011-01-12 09:06:06 +00003955 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003956 PointeeTy = IntTy;
3957 }
3958 }
3959}
3960
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003961void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00003962 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003963 // We follow the behavior of gcc, expanding structures which are
3964 // directly pointed to, and expanding embedded structures. Note that
3965 // these rules are sufficient to prevent recursive encoding of the
3966 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003967 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003968 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003969}
3970
David Chisnall64fd7e82010-06-04 01:10:52 +00003971static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3972 switch (T->getAs<BuiltinType>()->getKind()) {
3973 default: assert(0 && "Unhandled builtin type kind");
3974 case BuiltinType::Void: return 'v';
3975 case BuiltinType::Bool: return 'B';
3976 case BuiltinType::Char_U:
3977 case BuiltinType::UChar: return 'C';
3978 case BuiltinType::UShort: return 'S';
3979 case BuiltinType::UInt: return 'I';
3980 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00003981 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00003982 case BuiltinType::UInt128: return 'T';
3983 case BuiltinType::ULongLong: return 'Q';
3984 case BuiltinType::Char_S:
3985 case BuiltinType::SChar: return 'c';
3986 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00003987 case BuiltinType::WChar_S:
3988 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00003989 case BuiltinType::Int: return 'i';
3990 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00003991 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00003992 case BuiltinType::LongLong: return 'q';
3993 case BuiltinType::Int128: return 't';
3994 case BuiltinType::Float: return 'f';
3995 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00003996 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00003997 }
3998}
3999
Jay Foad4ba2a172011-01-12 09:06:06 +00004000static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004001 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004002 const Expr *E = FD->getBitWidth();
4003 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004004 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004005 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4006 // The GNU runtime requires more information; bitfields are encoded as b,
4007 // then the offset (in bits) of the first element, then the type of the
4008 // bitfield, then the size in bits. For example, in this structure:
4009 //
4010 // struct
4011 // {
4012 // int integer;
4013 // int flags:2;
4014 // };
4015 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4016 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4017 // information is not especially sensible, but we're stuck with it for
4018 // compatibility with GCC, although providing it breaks anything that
4019 // actually uses runtime introspection and wants to work on both runtimes...
4020 if (!Ctx->getLangOptions().NeXTRuntime) {
4021 const RecordDecl *RD = FD->getParent();
4022 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4023 // FIXME: This same linear search is also used in ExprConstant - it might
4024 // be better if the FieldDecl stored its offset. We'd be increasing the
4025 // size of the object slightly, but saving some time every time it is used.
4026 unsigned i = 0;
4027 for (RecordDecl::field_iterator Field = RD->field_begin(),
4028 FieldEnd = RD->field_end();
4029 Field != FieldEnd; (void)++Field, ++i) {
4030 if (*Field == FD)
4031 break;
4032 }
4033 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004034 if (T->isEnumeralType())
4035 S += 'i';
4036 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004037 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004038 }
4039 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004040 S += llvm::utostr(N);
4041}
4042
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004043// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004044void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4045 bool ExpandPointedToStructures,
4046 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004047 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004048 bool OutermostType,
Jay Foad4ba2a172011-01-12 09:06:06 +00004049 bool EncodingProperty) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004050 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004051 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004052 return EncodeBitField(this, S, T, FD);
4053 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004054 return;
4055 }
Mike Stump1eb44332009-09-09 15:08:12 +00004056
John McCall183700f2009-09-21 23:43:11 +00004057 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004058 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004059 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004060 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004061 return;
4062 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004063
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004064 // encoding for pointer or r3eference types.
4065 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004066 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004067 if (PT->isObjCSelType()) {
4068 S += ':';
4069 return;
4070 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004071 PointeeTy = PT->getPointeeType();
4072 }
4073 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4074 PointeeTy = RT->getPointeeType();
4075 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004076 bool isReadOnly = false;
4077 // For historical/compatibility reasons, the read-only qualifier of the
4078 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4079 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004080 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004081 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004082 if (OutermostType && T.isConstQualified()) {
4083 isReadOnly = true;
4084 S += 'r';
4085 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004086 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004087 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004088 while (P->getAs<PointerType>())
4089 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004090 if (P.isConstQualified()) {
4091 isReadOnly = true;
4092 S += 'r';
4093 }
4094 }
4095 if (isReadOnly) {
4096 // Another legacy compatibility encoding. Some ObjC qualifier and type
4097 // combinations need to be rearranged.
4098 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00004099 if (llvm::StringRef(S).endswith("nr"))
4100 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004101 }
Mike Stump1eb44332009-09-09 15:08:12 +00004102
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004103 if (PointeeTy->isCharType()) {
4104 // char pointer types should be encoded as '*' unless it is a
4105 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004106 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004107 S += '*';
4108 return;
4109 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004110 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004111 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4112 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4113 S += '#';
4114 return;
4115 }
4116 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4117 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4118 S += '@';
4119 return;
4120 }
4121 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004122 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004123 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004124 getLegacyIntegralTypeEncoding(PointeeTy);
4125
Mike Stump1eb44332009-09-09 15:08:12 +00004126 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004127 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004128 return;
4129 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004130
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004131 if (const ArrayType *AT =
4132 // Ignore type qualifiers etc.
4133 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004134 if (isa<IncompleteArrayType>(AT)) {
4135 // Incomplete arrays are encoded as a pointer to the array element.
4136 S += '^';
4137
Mike Stump1eb44332009-09-09 15:08:12 +00004138 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004139 false, ExpandStructures, FD);
4140 } else {
4141 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004142
Anders Carlsson559a8332009-02-22 01:38:57 +00004143 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4144 S += llvm::utostr(CAT->getSize().getZExtValue());
4145 else {
4146 //Variable length arrays are encoded as a regular array with 0 elements.
4147 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4148 S += '0';
4149 }
Mike Stump1eb44332009-09-09 15:08:12 +00004150
4151 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004152 false, ExpandStructures, FD);
4153 S += ']';
4154 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004155 return;
4156 }
Mike Stump1eb44332009-09-09 15:08:12 +00004157
John McCall183700f2009-09-21 23:43:11 +00004158 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004159 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004160 return;
4161 }
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Ted Kremenek6217b802009-07-29 21:53:49 +00004163 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004164 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004165 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004166 // Anonymous structures print as '?'
4167 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4168 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004169 if (ClassTemplateSpecializationDecl *Spec
4170 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4171 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4172 std::string TemplateArgsStr
4173 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004174 TemplateArgs.data(),
4175 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004176 (*this).PrintingPolicy);
4177
4178 S += TemplateArgsStr;
4179 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004180 } else {
4181 S += '?';
4182 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004183 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004184 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004185 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4186 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00004187 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004188 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004189 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00004190 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004191 S += '"';
4192 }
Mike Stump1eb44332009-09-09 15:08:12 +00004193
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004194 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004195 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004196 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004197 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004198 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004199 QualType qt = Field->getType();
4200 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00004201 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004202 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004203 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004204 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004205 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004206 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004207 return;
4208 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004209
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004210 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004211 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004212 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004213 else
4214 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004215 return;
4216 }
Mike Stump1eb44332009-09-09 15:08:12 +00004217
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004218 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004219 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004220 return;
4221 }
Mike Stump1eb44332009-09-09 15:08:12 +00004222
John McCallc12c5bb2010-05-15 11:32:37 +00004223 // Ignore protocol qualifiers when mangling at this level.
4224 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4225 T = OT->getBaseType();
4226
John McCall0953e762009-09-24 19:53:00 +00004227 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004228 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004229 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004230 S += '{';
4231 const IdentifierInfo *II = OI->getIdentifier();
4232 S += II->getName();
4233 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004234 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4235 DeepCollectObjCIvars(OI, true, Ivars);
4236 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4237 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4238 if (Field->isBitField())
4239 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004240 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004241 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004242 }
4243 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004244 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004245 }
Mike Stump1eb44332009-09-09 15:08:12 +00004246
John McCall183700f2009-09-21 23:43:11 +00004247 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004248 if (OPT->isObjCIdType()) {
4249 S += '@';
4250 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004251 }
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Steve Naroff27d20a22009-10-28 22:03:49 +00004253 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4254 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4255 // Since this is a binary compatibility issue, need to consult with runtime
4256 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004257 S += '#';
4258 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004259 }
Mike Stump1eb44332009-09-09 15:08:12 +00004260
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004261 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004262 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004263 ExpandPointedToStructures,
4264 ExpandStructures, FD);
4265 if (FD || EncodingProperty) {
4266 // Note that we do extended encoding of protocol qualifer list
4267 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004268 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004269 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4270 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004271 S += '<';
4272 S += (*I)->getNameAsString();
4273 S += '>';
4274 }
4275 S += '"';
4276 }
4277 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004278 }
Mike Stump1eb44332009-09-09 15:08:12 +00004279
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004280 QualType PointeeTy = OPT->getPointeeType();
4281 if (!EncodingProperty &&
4282 isa<TypedefType>(PointeeTy.getTypePtr())) {
4283 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004284 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004285 // {...};
4286 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004287 getObjCEncodingForTypeImpl(PointeeTy, S,
4288 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004289 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004290 return;
4291 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004292
4293 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004294 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004295 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004296 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004297 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4298 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004299 S += '<';
4300 S += (*I)->getNameAsString();
4301 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004302 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004303 S += '"';
4304 }
4305 return;
4306 }
Mike Stump1eb44332009-09-09 15:08:12 +00004307
John McCall532ec7b2010-05-17 23:56:34 +00004308 // gcc just blithely ignores member pointers.
4309 // TODO: maybe there should be a mangling for these
4310 if (T->getAs<MemberPointerType>())
4311 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004312
4313 if (T->isVectorType()) {
4314 // This matches gcc's encoding, even though technically it is
4315 // insufficient.
4316 // FIXME. We should do a better job than gcc.
4317 return;
4318 }
4319
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004320 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004321}
4322
Mike Stump1eb44332009-09-09 15:08:12 +00004323void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004324 std::string& S) const {
4325 if (QT & Decl::OBJC_TQ_In)
4326 S += 'n';
4327 if (QT & Decl::OBJC_TQ_Inout)
4328 S += 'N';
4329 if (QT & Decl::OBJC_TQ_Out)
4330 S += 'o';
4331 if (QT & Decl::OBJC_TQ_Bycopy)
4332 S += 'O';
4333 if (QT & Decl::OBJC_TQ_Byref)
4334 S += 'R';
4335 if (QT & Decl::OBJC_TQ_Oneway)
4336 S += 'V';
4337}
4338
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004339void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004340 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004341
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004342 BuiltinVaListType = T;
4343}
4344
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004345void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004346 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004347}
4348
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004349void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004350 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004351}
4352
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004353void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004354 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004355}
4356
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004357void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004358 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004359}
4360
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004361void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004362 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004363 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004364
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004365 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004366}
4367
John McCall0bd6feb2009-12-02 08:04:21 +00004368/// \brief Retrieve the template name that corresponds to a non-empty
4369/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004370TemplateName
4371ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4372 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004373 unsigned size = End - Begin;
4374 assert(size > 1 && "set is not overloaded!");
4375
4376 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4377 size * sizeof(FunctionTemplateDecl*));
4378 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4379
4380 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004381 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004382 NamedDecl *D = *I;
4383 assert(isa<FunctionTemplateDecl>(D) ||
4384 (isa<UsingShadowDecl>(D) &&
4385 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4386 *Storage++ = D;
4387 }
4388
4389 return TemplateName(OT);
4390}
4391
Douglas Gregor7532dc62009-03-30 22:58:21 +00004392/// \brief Retrieve the template name that represents a qualified
4393/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004394TemplateName
4395ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4396 bool TemplateKeyword,
4397 TemplateDecl *Template) const {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004398 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004399 llvm::FoldingSetNodeID ID;
4400 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4401
4402 void *InsertPos = 0;
4403 QualifiedTemplateName *QTN =
4404 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4405 if (!QTN) {
4406 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4407 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4408 }
4409
4410 return TemplateName(QTN);
4411}
4412
4413/// \brief Retrieve the template name that represents a dependent
4414/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004415TemplateName
4416ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4417 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004418 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004419 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004420
4421 llvm::FoldingSetNodeID ID;
4422 DependentTemplateName::Profile(ID, NNS, Name);
4423
4424 void *InsertPos = 0;
4425 DependentTemplateName *QTN =
4426 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4427
4428 if (QTN)
4429 return TemplateName(QTN);
4430
4431 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4432 if (CanonNNS == NNS) {
4433 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4434 } else {
4435 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4436 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004437 DependentTemplateName *CheckQTN =
4438 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4439 assert(!CheckQTN && "Dependent type name canonicalization broken");
4440 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004441 }
4442
4443 DependentTemplateNames.InsertNode(QTN, InsertPos);
4444 return TemplateName(QTN);
4445}
4446
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004447/// \brief Retrieve the template name that represents a dependent
4448/// template name such as \c MetaFun::template operator+.
4449TemplateName
4450ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004451 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004452 assert((!NNS || NNS->isDependent()) &&
4453 "Nested name specifier must be dependent");
4454
4455 llvm::FoldingSetNodeID ID;
4456 DependentTemplateName::Profile(ID, NNS, Operator);
4457
4458 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004459 DependentTemplateName *QTN
4460 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004461
4462 if (QTN)
4463 return TemplateName(QTN);
4464
4465 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4466 if (CanonNNS == NNS) {
4467 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4468 } else {
4469 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4470 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004471
4472 DependentTemplateName *CheckQTN
4473 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4474 assert(!CheckQTN && "Dependent template name canonicalization broken");
4475 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004476 }
4477
4478 DependentTemplateNames.InsertNode(QTN, InsertPos);
4479 return TemplateName(QTN);
4480}
4481
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004482TemplateName
4483ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4484 const TemplateArgument &ArgPack) const {
4485 ASTContext &Self = const_cast<ASTContext &>(*this);
4486 llvm::FoldingSetNodeID ID;
4487 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4488
4489 void *InsertPos = 0;
4490 SubstTemplateTemplateParmPackStorage *Subst
4491 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4492
4493 if (!Subst) {
4494 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4495 ArgPack.pack_size(),
4496 ArgPack.pack_begin());
4497 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4498 }
4499
4500 return TemplateName(Subst);
4501}
4502
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004503/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004504/// TargetInfo, produce the corresponding type. The unsigned @p Type
4505/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004506CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004507 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004508 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004509 case TargetInfo::SignedShort: return ShortTy;
4510 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4511 case TargetInfo::SignedInt: return IntTy;
4512 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4513 case TargetInfo::SignedLong: return LongTy;
4514 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4515 case TargetInfo::SignedLongLong: return LongLongTy;
4516 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4517 }
4518
4519 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004520 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004521}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004522
4523//===----------------------------------------------------------------------===//
4524// Type Predicates.
4525//===----------------------------------------------------------------------===//
4526
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004527/// isObjCNSObjectType - Return true if this is an NSObject object using
4528/// NSObject attribute on a c-style pointer type.
4529/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004530/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004531///
4532bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCallf4c73712011-01-19 06:33:43 +00004533 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004534 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004535 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004536 return true;
4537 }
Mike Stump1eb44332009-09-09 15:08:12 +00004538 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004539}
4540
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004541/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4542/// garbage collection attribute.
4543///
John McCallae278a32011-01-12 00:34:59 +00004544Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4545 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4546 return Qualifiers::GCNone;
4547
4548 assert(getLangOptions().ObjC1);
4549 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4550
4551 // Default behaviour under objective-C's gc is for ObjC pointers
4552 // (or pointers to them) be treated as though they were declared
4553 // as __strong.
4554 if (GCAttrs == Qualifiers::GCNone) {
4555 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4556 return Qualifiers::Strong;
4557 else if (Ty->isPointerType())
4558 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4559 } else {
4560 // It's not valid to set GC attributes on anything that isn't a
4561 // pointer.
4562#ifndef NDEBUG
4563 QualType CT = Ty->getCanonicalTypeInternal();
4564 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4565 CT = AT->getElementType();
4566 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4567#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004568 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004569 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004570}
4571
Chris Lattner6ac46a42008-04-07 06:51:04 +00004572//===----------------------------------------------------------------------===//
4573// Type Compatibility Testing
4574//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004575
Mike Stump1eb44332009-09-09 15:08:12 +00004576/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004577/// compatible.
4578static bool areCompatVectorTypes(const VectorType *LHS,
4579 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004580 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004581 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004582 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004583}
4584
Douglas Gregor255210e2010-08-06 10:14:59 +00004585bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4586 QualType SecondVec) {
4587 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4588 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4589
4590 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4591 return true;
4592
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004593 // Treat Neon vector types and most AltiVec vector types as if they are the
4594 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004595 const VectorType *First = FirstVec->getAs<VectorType>();
4596 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004597 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004598 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004599 First->getVectorKind() != VectorType::AltiVecPixel &&
4600 First->getVectorKind() != VectorType::AltiVecBool &&
4601 Second->getVectorKind() != VectorType::AltiVecPixel &&
4602 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004603 return true;
4604
4605 return false;
4606}
4607
Steve Naroff4084c302009-07-23 01:01:38 +00004608//===----------------------------------------------------------------------===//
4609// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4610//===----------------------------------------------------------------------===//
4611
4612/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4613/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004614bool
4615ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4616 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004617 if (lProto == rProto)
4618 return true;
4619 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4620 E = rProto->protocol_end(); PI != E; ++PI)
4621 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4622 return true;
4623 return false;
4624}
4625
Steve Naroff4084c302009-07-23 01:01:38 +00004626/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4627/// return true if lhs's protocols conform to rhs's protocol; false
4628/// otherwise.
4629bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4630 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4631 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4632 return false;
4633}
4634
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004635/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4636/// Class<p1, ...>.
4637bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4638 QualType rhs) {
4639 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4640 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4641 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4642
4643 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4644 E = lhsQID->qual_end(); I != E; ++I) {
4645 bool match = false;
4646 ObjCProtocolDecl *lhsProto = *I;
4647 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4648 E = rhsOPT->qual_end(); J != E; ++J) {
4649 ObjCProtocolDecl *rhsProto = *J;
4650 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4651 match = true;
4652 break;
4653 }
4654 }
4655 if (!match)
4656 return false;
4657 }
4658 return true;
4659}
4660
Steve Naroff4084c302009-07-23 01:01:38 +00004661/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4662/// ObjCQualifiedIDType.
4663bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4664 bool compare) {
4665 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004666 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004667 lhs->isObjCIdType() || lhs->isObjCClassType())
4668 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004669 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004670 rhs->isObjCIdType() || rhs->isObjCClassType())
4671 return true;
4672
4673 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004674 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004675
Steve Naroff4084c302009-07-23 01:01:38 +00004676 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004677
Steve Naroff4084c302009-07-23 01:01:38 +00004678 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004679 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004680 // make sure we check the class hierarchy.
4681 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4682 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4683 E = lhsQID->qual_end(); I != E; ++I) {
4684 // when comparing an id<P> on lhs with a static type on rhs,
4685 // see if static class implements all of id's protocols, directly or
4686 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004687 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004688 return false;
4689 }
4690 }
4691 // If there are no qualifiers and no interface, we have an 'id'.
4692 return true;
4693 }
Mike Stump1eb44332009-09-09 15:08:12 +00004694 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004695 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4696 E = lhsQID->qual_end(); I != E; ++I) {
4697 ObjCProtocolDecl *lhsProto = *I;
4698 bool match = false;
4699
4700 // when comparing an id<P> on lhs with a static type on rhs,
4701 // see if static class implements all of id's protocols, directly or
4702 // through its super class and categories.
4703 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4704 E = rhsOPT->qual_end(); J != E; ++J) {
4705 ObjCProtocolDecl *rhsProto = *J;
4706 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4707 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4708 match = true;
4709 break;
4710 }
4711 }
Mike Stump1eb44332009-09-09 15:08:12 +00004712 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004713 // make sure we check the class hierarchy.
4714 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4715 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4716 E = lhsQID->qual_end(); I != E; ++I) {
4717 // when comparing an id<P> on lhs with a static type on rhs,
4718 // see if static class implements all of id's protocols, directly or
4719 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004720 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004721 match = true;
4722 break;
4723 }
4724 }
4725 }
4726 if (!match)
4727 return false;
4728 }
Mike Stump1eb44332009-09-09 15:08:12 +00004729
Steve Naroff4084c302009-07-23 01:01:38 +00004730 return true;
4731 }
Mike Stump1eb44332009-09-09 15:08:12 +00004732
Steve Naroff4084c302009-07-23 01:01:38 +00004733 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4734 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4735
Mike Stump1eb44332009-09-09 15:08:12 +00004736 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004737 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004738 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004739 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4740 E = lhsOPT->qual_end(); I != E; ++I) {
4741 ObjCProtocolDecl *lhsProto = *I;
4742 bool match = false;
4743
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004744 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00004745 // see if static class implements all of id's protocols, directly or
4746 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004747 // First, lhs protocols in the qualifier list must be found, direct
4748 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00004749 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4750 E = rhsQID->qual_end(); J != E; ++J) {
4751 ObjCProtocolDecl *rhsProto = *J;
4752 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4753 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4754 match = true;
4755 break;
4756 }
4757 }
4758 if (!match)
4759 return false;
4760 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004761
4762 // Static class's protocols, or its super class or category protocols
4763 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4764 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4765 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4766 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4767 // This is rather dubious but matches gcc's behavior. If lhs has
4768 // no type qualifier and its class has no static protocol(s)
4769 // assume that it is mismatch.
4770 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4771 return false;
4772 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4773 LHSInheritedProtocols.begin(),
4774 E = LHSInheritedProtocols.end(); I != E; ++I) {
4775 bool match = false;
4776 ObjCProtocolDecl *lhsProto = (*I);
4777 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4778 E = rhsQID->qual_end(); J != E; ++J) {
4779 ObjCProtocolDecl *rhsProto = *J;
4780 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4781 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4782 match = true;
4783 break;
4784 }
4785 }
4786 if (!match)
4787 return false;
4788 }
4789 }
Steve Naroff4084c302009-07-23 01:01:38 +00004790 return true;
4791 }
4792 return false;
4793}
4794
Eli Friedman3d815e72008-08-22 00:56:42 +00004795/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004796/// compatible for assignment from RHS to LHS. This handles validation of any
4797/// protocol qualifiers on the LHS or RHS.
4798///
Steve Naroff14108da2009-07-10 23:34:53 +00004799bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4800 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004801 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4802 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4803
Steve Naroffde2e22d2009-07-15 18:40:39 +00004804 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004805 if (LHS->isObjCUnqualifiedIdOrClass() ||
4806 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004807 return true;
4808
John McCallc12c5bb2010-05-15 11:32:37 +00004809 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004810 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4811 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004812 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004813
4814 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4815 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4816 QualType(RHSOPT,0));
4817
John McCallc12c5bb2010-05-15 11:32:37 +00004818 // If we have 2 user-defined types, fall into that path.
4819 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004820 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004821
Steve Naroff4084c302009-07-23 01:01:38 +00004822 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004823}
4824
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004825/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4826/// for providing type-safty for objective-c pointers used to pass/return
4827/// arguments in block literals. When passed as arguments, passing 'A*' where
4828/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4829/// not OK. For the return type, the opposite is not OK.
4830bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4831 const ObjCObjectPointerType *LHSOPT,
4832 const ObjCObjectPointerType *RHSOPT) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004833 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004834 return true;
4835
4836 if (LHSOPT->isObjCBuiltinType()) {
4837 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4838 }
4839
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004840 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004841 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4842 QualType(RHSOPT,0),
4843 false);
4844
4845 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4846 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4847 if (LHS && RHS) { // We have 2 user-defined types.
4848 if (LHS != RHS) {
4849 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4850 return false;
4851 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4852 return true;
4853 }
4854 else
4855 return true;
4856 }
4857 return false;
4858}
4859
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004860/// getIntersectionOfProtocols - This routine finds the intersection of set
4861/// of protocols inherited from two distinct objective-c pointer objects.
4862/// It is used to build composite qualifier list of the composite type of
4863/// the conditional expression involving two objective-c pointer objects.
4864static
4865void getIntersectionOfProtocols(ASTContext &Context,
4866 const ObjCObjectPointerType *LHSOPT,
4867 const ObjCObjectPointerType *RHSOPT,
4868 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4869
John McCallc12c5bb2010-05-15 11:32:37 +00004870 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4871 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4872 assert(LHS->getInterface() && "LHS must have an interface base");
4873 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004874
4875 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4876 unsigned LHSNumProtocols = LHS->getNumProtocols();
4877 if (LHSNumProtocols > 0)
4878 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4879 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004880 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004881 Context.CollectInheritedProtocols(LHS->getInterface(),
4882 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004883 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4884 LHSInheritedProtocols.end());
4885 }
4886
4887 unsigned RHSNumProtocols = RHS->getNumProtocols();
4888 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004889 ObjCProtocolDecl **RHSProtocols =
4890 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004891 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4892 if (InheritedProtocolSet.count(RHSProtocols[i]))
4893 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4894 }
4895 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004896 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004897 Context.CollectInheritedProtocols(RHS->getInterface(),
4898 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004899 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4900 RHSInheritedProtocols.begin(),
4901 E = RHSInheritedProtocols.end(); I != E; ++I)
4902 if (InheritedProtocolSet.count((*I)))
4903 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004904 }
4905}
4906
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004907/// areCommonBaseCompatible - Returns common base class of the two classes if
4908/// one found. Note that this is O'2 algorithm. But it will be called as the
4909/// last type comparison in a ?-exp of ObjC pointer types before a
4910/// warning is issued. So, its invokation is extremely rare.
4911QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004912 const ObjCObjectPointerType *Lptr,
4913 const ObjCObjectPointerType *Rptr) {
4914 const ObjCObjectType *LHS = Lptr->getObjectType();
4915 const ObjCObjectType *RHS = Rptr->getObjectType();
4916 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4917 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4918 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004919 return QualType();
4920
John McCallc12c5bb2010-05-15 11:32:37 +00004921 while ((LDecl = LDecl->getSuperClass())) {
4922 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004923 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004924 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4925 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4926
4927 QualType Result = QualType(LHS, 0);
4928 if (!Protocols.empty())
4929 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4930 Result = getObjCObjectPointerType(Result);
4931 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004932 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004933 }
4934
4935 return QualType();
4936}
4937
John McCallc12c5bb2010-05-15 11:32:37 +00004938bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4939 const ObjCObjectType *RHS) {
4940 assert(LHS->getInterface() && "LHS is not an interface type");
4941 assert(RHS->getInterface() && "RHS is not an interface type");
4942
Chris Lattner6ac46a42008-04-07 06:51:04 +00004943 // Verify that the base decls are compatible: the RHS must be a subclass of
4944 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004945 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004946 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004947
Chris Lattner6ac46a42008-04-07 06:51:04 +00004948 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4949 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004950 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004951 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004952
Chris Lattner6ac46a42008-04-07 06:51:04 +00004953 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4954 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004955 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004956 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004957
John McCallc12c5bb2010-05-15 11:32:37 +00004958 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4959 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004960 LHSPI != LHSPE; LHSPI++) {
4961 bool RHSImplementsProtocol = false;
4962
4963 // If the RHS doesn't implement the protocol on the left, the types
4964 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004965 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4966 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004967 RHSPI != RHSPE; RHSPI++) {
4968 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004969 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004970 break;
4971 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004972 }
4973 // FIXME: For better diagnostics, consider passing back the protocol name.
4974 if (!RHSImplementsProtocol)
4975 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004976 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004977 // The RHS implements all protocols listed on the LHS.
4978 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004979}
4980
Steve Naroff389bf462009-02-12 17:52:19 +00004981bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4982 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004983 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4984 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004985
Steve Naroff14108da2009-07-10 23:34:53 +00004986 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004987 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004988
4989 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4990 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004991}
4992
Douglas Gregor569c3162010-08-07 11:51:51 +00004993bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
4994 return canAssignObjCInterfaces(
4995 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
4996 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
4997}
4998
Mike Stump1eb44332009-09-09 15:08:12 +00004999/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005000/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005001/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005002/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005003bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5004 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005005 if (getLangOptions().CPlusPlus)
5006 return hasSameType(LHS, RHS);
5007
Douglas Gregor447234d2010-07-29 15:18:02 +00005008 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005009}
5010
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005011bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5012 return !mergeTypes(LHS, RHS, true).isNull();
5013}
5014
Peter Collingbourne48466752010-10-24 18:30:18 +00005015/// mergeTransparentUnionType - if T is a transparent union type and a member
5016/// of T is compatible with SubType, return the merged type, else return
5017/// QualType()
5018QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5019 bool OfBlockPointer,
5020 bool Unqualified) {
5021 if (const RecordType *UT = T->getAsUnionType()) {
5022 RecordDecl *UD = UT->getDecl();
5023 if (UD->hasAttr<TransparentUnionAttr>()) {
5024 for (RecordDecl::field_iterator it = UD->field_begin(),
5025 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005026 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005027 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5028 if (!MT.isNull())
5029 return MT;
5030 }
5031 }
5032 }
5033
5034 return QualType();
5035}
5036
5037/// mergeFunctionArgumentTypes - merge two types which appear as function
5038/// argument types
5039QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5040 bool OfBlockPointer,
5041 bool Unqualified) {
5042 // GNU extension: two types are compatible if they appear as a function
5043 // argument, one of the types is a transparent union type and the other
5044 // type is compatible with a union member
5045 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5046 Unqualified);
5047 if (!lmerge.isNull())
5048 return lmerge;
5049
5050 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5051 Unqualified);
5052 if (!rmerge.isNull())
5053 return rmerge;
5054
5055 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5056}
5057
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005058QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005059 bool OfBlockPointer,
5060 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005061 const FunctionType *lbase = lhs->getAs<FunctionType>();
5062 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005063 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5064 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005065 bool allLTypes = true;
5066 bool allRTypes = true;
5067
5068 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005069 QualType retType;
5070 if (OfBlockPointer)
Douglas Gregor447234d2010-07-29 15:18:02 +00005071 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true,
5072 Unqualified);
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005073 else
John McCall8cc246c2010-12-15 01:06:38 +00005074 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5075 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005076 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005077
5078 if (Unqualified)
5079 retType = retType.getUnqualifiedType();
5080
5081 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5082 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5083 if (Unqualified) {
5084 LRetType = LRetType.getUnqualifiedType();
5085 RRetType = RRetType.getUnqualifiedType();
5086 }
5087
5088 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005089 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005090 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005091 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005092
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005093 // FIXME: double check this
5094 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5095 // rbase->getRegParmAttr() != 0 &&
5096 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005097 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5098 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005099
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005100 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005101 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005102 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005103
John McCall8cc246c2010-12-15 01:06:38 +00005104 // Regparm is part of the calling convention.
5105 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5106 return QualType();
5107
5108 // It's noreturn if either type is.
5109 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5110 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5111 if (NoReturn != lbaseInfo.getNoReturn())
5112 allLTypes = false;
5113 if (NoReturn != rbaseInfo.getNoReturn())
5114 allRTypes = false;
5115
5116 FunctionType::ExtInfo einfo(NoReturn,
5117 lbaseInfo.getRegParm(),
5118 lbaseInfo.getCC());
John McCalle23cf432010-12-14 08:05:40 +00005119
Eli Friedman3d815e72008-08-22 00:56:42 +00005120 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005121 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5122 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005123 unsigned lproto_nargs = lproto->getNumArgs();
5124 unsigned rproto_nargs = rproto->getNumArgs();
5125
5126 // Compatible functions must have the same number of arguments
5127 if (lproto_nargs != rproto_nargs)
5128 return QualType();
5129
5130 // Variadic and non-variadic functions aren't compatible
5131 if (lproto->isVariadic() != rproto->isVariadic())
5132 return QualType();
5133
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005134 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5135 return QualType();
5136
Eli Friedman3d815e72008-08-22 00:56:42 +00005137 // Check argument compatibility
5138 llvm::SmallVector<QualType, 10> types;
5139 for (unsigned i = 0; i < lproto_nargs; i++) {
5140 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5141 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005142 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5143 OfBlockPointer,
5144 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005145 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005146
5147 if (Unqualified)
5148 argtype = argtype.getUnqualifiedType();
5149
Eli Friedman3d815e72008-08-22 00:56:42 +00005150 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005151 if (Unqualified) {
5152 largtype = largtype.getUnqualifiedType();
5153 rargtype = rargtype.getUnqualifiedType();
5154 }
5155
Chris Lattner61710852008-10-05 17:34:18 +00005156 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5157 allLTypes = false;
5158 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5159 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005160 }
5161 if (allLTypes) return lhs;
5162 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005163
5164 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5165 EPI.ExtInfo = einfo;
5166 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005167 }
5168
5169 if (lproto) allRTypes = false;
5170 if (rproto) allLTypes = false;
5171
Douglas Gregor72564e72009-02-26 23:50:07 +00005172 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005173 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005174 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005175 if (proto->isVariadic()) return QualType();
5176 // Check that the types are compatible with the types that
5177 // would result from default argument promotions (C99 6.7.5.3p15).
5178 // The only types actually affected are promotable integer
5179 // types and floats, which would be passed as a different
5180 // type depending on whether the prototype is visible.
5181 unsigned proto_nargs = proto->getNumArgs();
5182 for (unsigned i = 0; i < proto_nargs; ++i) {
5183 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005184
5185 // Look at the promotion type of enum types, since that is the type used
5186 // to pass enum values.
5187 if (const EnumType *Enum = argTy->getAs<EnumType>())
5188 argTy = Enum->getDecl()->getPromotionType();
5189
Eli Friedman3d815e72008-08-22 00:56:42 +00005190 if (argTy->isPromotableIntegerType() ||
5191 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5192 return QualType();
5193 }
5194
5195 if (allLTypes) return lhs;
5196 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005197
5198 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5199 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005200 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005201 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005202 }
5203
5204 if (allLTypes) return lhs;
5205 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005206 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005207}
5208
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005209QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005210 bool OfBlockPointer,
5211 bool Unqualified) {
Bill Wendling43d69752007-12-03 07:33:35 +00005212 // C++ [expr]: If an expression initially has the type "reference to T", the
5213 // type is adjusted to "T" prior to any further analysis, the expression
5214 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005215 // expression is an lvalue unless the reference is an rvalue reference and
5216 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005217 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5218 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005219
5220 if (Unqualified) {
5221 LHS = LHS.getUnqualifiedType();
5222 RHS = RHS.getUnqualifiedType();
5223 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005224
Eli Friedman3d815e72008-08-22 00:56:42 +00005225 QualType LHSCan = getCanonicalType(LHS),
5226 RHSCan = getCanonicalType(RHS);
5227
5228 // If two types are identical, they are compatible.
5229 if (LHSCan == RHSCan)
5230 return LHS;
5231
John McCall0953e762009-09-24 19:53:00 +00005232 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005233 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5234 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005235 if (LQuals != RQuals) {
5236 // If any of these qualifiers are different, we have a type
5237 // mismatch.
5238 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5239 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5240 return QualType();
5241
5242 // Exactly one GC qualifier difference is allowed: __strong is
5243 // okay if the other type has no GC qualifier but is an Objective
5244 // C object pointer (i.e. implicitly strong by default). We fix
5245 // this by pretending that the unqualified type was actually
5246 // qualified __strong.
5247 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5248 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5249 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5250
5251 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5252 return QualType();
5253
5254 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5255 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5256 }
5257 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5258 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5259 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005260 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005261 }
5262
5263 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005264
Eli Friedman852d63b2009-06-01 01:22:52 +00005265 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5266 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005267
Chris Lattner1adb8832008-01-14 05:45:46 +00005268 // We want to consider the two function types to be the same for these
5269 // comparisons, just force one to the other.
5270 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5271 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005272
5273 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005274 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5275 LHSClass = Type::ConstantArray;
5276 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5277 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005278
John McCallc12c5bb2010-05-15 11:32:37 +00005279 // ObjCInterfaces are just specialized ObjCObjects.
5280 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5281 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5282
Nate Begeman213541a2008-04-18 23:10:10 +00005283 // Canonicalize ExtVector -> Vector.
5284 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5285 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005286
Chris Lattnera36a61f2008-04-07 05:43:21 +00005287 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005288 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005289 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005290 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005291 // Compatibility is based on the underlying type, not the promotion
5292 // type.
John McCall183700f2009-09-21 23:43:11 +00005293 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005294 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5295 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005296 }
John McCall183700f2009-09-21 23:43:11 +00005297 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005298 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5299 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005300 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005301
Eli Friedman3d815e72008-08-22 00:56:42 +00005302 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005303 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005304
Steve Naroff4a746782008-01-09 22:43:08 +00005305 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005306 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005307#define TYPE(Class, Base)
5308#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005309#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005310#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5311#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5312#include "clang/AST/TypeNodes.def"
5313 assert(false && "Non-canonical and dependent types shouldn't get here");
5314 return QualType();
5315
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005316 case Type::LValueReference:
5317 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005318 case Type::MemberPointer:
5319 assert(false && "C++ should never be in mergeTypes");
5320 return QualType();
5321
John McCallc12c5bb2010-05-15 11:32:37 +00005322 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005323 case Type::IncompleteArray:
5324 case Type::VariableArray:
5325 case Type::FunctionProto:
5326 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005327 assert(false && "Types are eliminated above");
5328 return QualType();
5329
Chris Lattner1adb8832008-01-14 05:45:46 +00005330 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005331 {
5332 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005333 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5334 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005335 if (Unqualified) {
5336 LHSPointee = LHSPointee.getUnqualifiedType();
5337 RHSPointee = RHSPointee.getUnqualifiedType();
5338 }
5339 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5340 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005341 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005342 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005343 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005344 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005345 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005346 return getPointerType(ResultType);
5347 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005348 case Type::BlockPointer:
5349 {
5350 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005351 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5352 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005353 if (Unqualified) {
5354 LHSPointee = LHSPointee.getUnqualifiedType();
5355 RHSPointee = RHSPointee.getUnqualifiedType();
5356 }
5357 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5358 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005359 if (ResultType.isNull()) return QualType();
5360 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5361 return LHS;
5362 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5363 return RHS;
5364 return getBlockPointerType(ResultType);
5365 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005366 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005367 {
5368 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5369 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5370 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5371 return QualType();
5372
5373 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5374 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005375 if (Unqualified) {
5376 LHSElem = LHSElem.getUnqualifiedType();
5377 RHSElem = RHSElem.getUnqualifiedType();
5378 }
5379
5380 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005381 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005382 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5383 return LHS;
5384 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5385 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005386 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5387 ArrayType::ArraySizeModifier(), 0);
5388 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5389 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005390 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5391 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005392 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5393 return LHS;
5394 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5395 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005396 if (LVAT) {
5397 // FIXME: This isn't correct! But tricky to implement because
5398 // the array's size has to be the size of LHS, but the type
5399 // has to be different.
5400 return LHS;
5401 }
5402 if (RVAT) {
5403 // FIXME: This isn't correct! But tricky to implement because
5404 // the array's size has to be the size of RHS, but the type
5405 // has to be different.
5406 return RHS;
5407 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005408 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5409 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005410 return getIncompleteArrayType(ResultType,
5411 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005412 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005413 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005414 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005415 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005416 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005417 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005418 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005419 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005420 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005421 case Type::Complex:
5422 // Distinct complex types are incompatible.
5423 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005424 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005425 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005426 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5427 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005428 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005429 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005430 case Type::ObjCObject: {
5431 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005432 // FIXME: This should be type compatibility, e.g. whether
5433 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005434 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5435 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5436 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005437 return LHS;
5438
Eli Friedman3d815e72008-08-22 00:56:42 +00005439 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005440 }
Steve Naroff14108da2009-07-10 23:34:53 +00005441 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005442 if (OfBlockPointer) {
5443 if (canAssignObjCInterfacesInBlockPointer(
5444 LHS->getAs<ObjCObjectPointerType>(),
5445 RHS->getAs<ObjCObjectPointerType>()))
5446 return LHS;
5447 return QualType();
5448 }
John McCall183700f2009-09-21 23:43:11 +00005449 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5450 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005451 return LHS;
5452
Steve Naroffbc76dd02008-12-10 22:14:21 +00005453 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005454 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005455 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005456
5457 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005458}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005459
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005460/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5461/// 'RHS' attributes and returns the merged version; including for function
5462/// return types.
5463QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5464 QualType LHSCan = getCanonicalType(LHS),
5465 RHSCan = getCanonicalType(RHS);
5466 // If two types are identical, they are compatible.
5467 if (LHSCan == RHSCan)
5468 return LHS;
5469 if (RHSCan->isFunctionType()) {
5470 if (!LHSCan->isFunctionType())
5471 return QualType();
5472 QualType OldReturnType =
5473 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5474 QualType NewReturnType =
5475 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5476 QualType ResReturnType =
5477 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5478 if (ResReturnType.isNull())
5479 return QualType();
5480 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5481 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5482 // In either case, use OldReturnType to build the new function type.
5483 const FunctionType *F = LHS->getAs<FunctionType>();
5484 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005485 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5486 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005487 QualType ResultType
5488 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005489 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005490 return ResultType;
5491 }
5492 }
5493 return QualType();
5494 }
5495
5496 // If the qualifiers are different, the types can still be merged.
5497 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5498 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5499 if (LQuals != RQuals) {
5500 // If any of these qualifiers are different, we have a type mismatch.
5501 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5502 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5503 return QualType();
5504
5505 // Exactly one GC qualifier difference is allowed: __strong is
5506 // okay if the other type has no GC qualifier but is an Objective
5507 // C object pointer (i.e. implicitly strong by default). We fix
5508 // this by pretending that the unqualified type was actually
5509 // qualified __strong.
5510 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5511 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5512 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5513
5514 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5515 return QualType();
5516
5517 if (GC_L == Qualifiers::Strong)
5518 return LHS;
5519 if (GC_R == Qualifiers::Strong)
5520 return RHS;
5521 return QualType();
5522 }
5523
5524 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5525 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5526 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5527 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5528 if (ResQT == LHSBaseQT)
5529 return LHS;
5530 if (ResQT == RHSBaseQT)
5531 return RHS;
5532 }
5533 return QualType();
5534}
5535
Chris Lattner5426bf62008-04-07 07:01:58 +00005536//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005537// Integer Predicates
5538//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005539
Jay Foad4ba2a172011-01-12 09:06:06 +00005540unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005541 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005542 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005543 if (T->isBooleanType())
5544 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005545 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005546 return (unsigned)getTypeSize(T);
5547}
5548
5549QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005550 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005551
5552 // Turn <4 x signed int> -> <4 x unsigned int>
5553 if (const VectorType *VTy = T->getAs<VectorType>())
5554 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005555 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005556
5557 // For enums, we return the unsigned version of the base type.
5558 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005559 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005560
5561 const BuiltinType *BTy = T->getAs<BuiltinType>();
5562 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005563 switch (BTy->getKind()) {
5564 case BuiltinType::Char_S:
5565 case BuiltinType::SChar:
5566 return UnsignedCharTy;
5567 case BuiltinType::Short:
5568 return UnsignedShortTy;
5569 case BuiltinType::Int:
5570 return UnsignedIntTy;
5571 case BuiltinType::Long:
5572 return UnsignedLongTy;
5573 case BuiltinType::LongLong:
5574 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005575 case BuiltinType::Int128:
5576 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005577 default:
5578 assert(0 && "Unexpected signed integer type");
5579 return QualType();
5580 }
5581}
5582
Douglas Gregor2cf26342009-04-09 22:27:44 +00005583ExternalASTSource::~ExternalASTSource() { }
5584
5585void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00005586
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005587ASTMutationListener::~ASTMutationListener() { }
5588
Chris Lattner86df27b2009-06-14 00:45:47 +00005589
5590//===----------------------------------------------------------------------===//
5591// Builtin Type Computation
5592//===----------------------------------------------------------------------===//
5593
5594/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005595/// pointer over the consumed characters. This returns the resultant type. If
5596/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5597/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5598/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005599///
5600/// RequiresICE is filled in on return to indicate whether the value is required
5601/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00005602static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005603 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005604 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005605 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005606 // Modifiers.
5607 int HowLong = 0;
5608 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005609 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005610
Chris Lattner33daae62010-10-01 22:42:38 +00005611 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005612 bool Done = false;
5613 while (!Done) {
5614 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005615 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005616 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005617 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005618 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005619 case 'S':
5620 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5621 assert(!Signed && "Can't use 'S' modifier multiple times!");
5622 Signed = true;
5623 break;
5624 case 'U':
5625 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5626 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5627 Unsigned = true;
5628 break;
5629 case 'L':
5630 assert(HowLong <= 2 && "Can't have LLLL modifier");
5631 ++HowLong;
5632 break;
5633 }
5634 }
5635
5636 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005637
Chris Lattner86df27b2009-06-14 00:45:47 +00005638 // Read the base type.
5639 switch (*Str++) {
5640 default: assert(0 && "Unknown builtin type letter!");
5641 case 'v':
5642 assert(HowLong == 0 && !Signed && !Unsigned &&
5643 "Bad modifiers used with 'v'!");
5644 Type = Context.VoidTy;
5645 break;
5646 case 'f':
5647 assert(HowLong == 0 && !Signed && !Unsigned &&
5648 "Bad modifiers used with 'f'!");
5649 Type = Context.FloatTy;
5650 break;
5651 case 'd':
5652 assert(HowLong < 2 && !Signed && !Unsigned &&
5653 "Bad modifiers used with 'd'!");
5654 if (HowLong)
5655 Type = Context.LongDoubleTy;
5656 else
5657 Type = Context.DoubleTy;
5658 break;
5659 case 's':
5660 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5661 if (Unsigned)
5662 Type = Context.UnsignedShortTy;
5663 else
5664 Type = Context.ShortTy;
5665 break;
5666 case 'i':
5667 if (HowLong == 3)
5668 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5669 else if (HowLong == 2)
5670 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5671 else if (HowLong == 1)
5672 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5673 else
5674 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5675 break;
5676 case 'c':
5677 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5678 if (Signed)
5679 Type = Context.SignedCharTy;
5680 else if (Unsigned)
5681 Type = Context.UnsignedCharTy;
5682 else
5683 Type = Context.CharTy;
5684 break;
5685 case 'b': // boolean
5686 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5687 Type = Context.BoolTy;
5688 break;
5689 case 'z': // size_t.
5690 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5691 Type = Context.getSizeType();
5692 break;
5693 case 'F':
5694 Type = Context.getCFConstantStringType();
5695 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00005696 case 'G':
5697 Type = Context.getObjCIdType();
5698 break;
5699 case 'H':
5700 Type = Context.getObjCSelType();
5701 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005702 case 'a':
5703 Type = Context.getBuiltinVaListType();
5704 assert(!Type.isNull() && "builtin va list type not initialized!");
5705 break;
5706 case 'A':
5707 // This is a "reference" to a va_list; however, what exactly
5708 // this means depends on how va_list is defined. There are two
5709 // different kinds of va_list: ones passed by value, and ones
5710 // passed by reference. An example of a by-value va_list is
5711 // x86, where va_list is a char*. An example of by-ref va_list
5712 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5713 // we want this argument to be a char*&; for x86-64, we want
5714 // it to be a __va_list_tag*.
5715 Type = Context.getBuiltinVaListType();
5716 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00005717 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00005718 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00005719 else
Chris Lattner86df27b2009-06-14 00:45:47 +00005720 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005721 break;
5722 case 'V': {
5723 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005724 unsigned NumElements = strtoul(Str, &End, 10);
5725 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00005726 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005727
Chris Lattner14e0e742010-10-01 22:53:11 +00005728 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5729 RequiresICE, false);
5730 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00005731
5732 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005733 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00005734 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00005735 break;
5736 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005737 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00005738 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5739 false);
5740 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00005741 Type = Context.getComplexType(ElementType);
5742 break;
5743 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005744 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005745 Type = Context.getFILEType();
5746 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005747 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005748 return QualType();
5749 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005750 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005751 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005752 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005753 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005754 else
5755 Type = Context.getjmp_bufType();
5756
Mike Stumpfd612db2009-07-28 23:47:15 +00005757 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005758 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005759 return QualType();
5760 }
5761 break;
Mike Stump782fa302009-07-28 02:25:19 +00005762 }
Mike Stump1eb44332009-09-09 15:08:12 +00005763
Chris Lattner33daae62010-10-01 22:42:38 +00005764 // If there are modifiers and if we're allowed to parse them, go for it.
5765 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00005766 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005767 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00005768 default: Done = true; --Str; break;
5769 case '*':
5770 case '&': {
5771 // Both pointers and references can have their pointee types
5772 // qualified with an address space.
5773 char *End;
5774 unsigned AddrSpace = strtoul(Str, &End, 10);
5775 if (End != Str && AddrSpace != 0) {
5776 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5777 Str = End;
5778 }
5779 if (c == '*')
5780 Type = Context.getPointerType(Type);
5781 else
5782 Type = Context.getLValueReferenceType(Type);
5783 break;
5784 }
5785 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5786 case 'C':
5787 Type = Type.withConst();
5788 break;
5789 case 'D':
5790 Type = Context.getVolatileType(Type);
5791 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005792 }
5793 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00005794
Chris Lattner14e0e742010-10-01 22:53:11 +00005795 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00005796 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00005797
Chris Lattner86df27b2009-06-14 00:45:47 +00005798 return Type;
5799}
5800
5801/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00005802QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00005803 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00005804 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00005805 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00005806
Chris Lattner86df27b2009-06-14 00:45:47 +00005807 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005808
Chris Lattner14e0e742010-10-01 22:53:11 +00005809 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00005810 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00005811 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5812 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005813 if (Error != GE_None)
5814 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00005815
5816 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5817
Chris Lattner86df27b2009-06-14 00:45:47 +00005818 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00005819 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005820 if (Error != GE_None)
5821 return QualType();
5822
Chris Lattner14e0e742010-10-01 22:53:11 +00005823 // If this argument is required to be an IntegerConstantExpression and the
5824 // caller cares, fill in the bitmask we return.
5825 if (RequiresICE && IntegerConstantArgs)
5826 *IntegerConstantArgs |= 1 << ArgTypes.size();
5827
Chris Lattner86df27b2009-06-14 00:45:47 +00005828 // Do array -> pointer decay. The builtin should use the decayed type.
5829 if (Ty->isArrayType())
5830 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005831
Chris Lattner86df27b2009-06-14 00:45:47 +00005832 ArgTypes.push_back(Ty);
5833 }
5834
5835 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5836 "'.' should only occur at end of builtin type list!");
5837
John McCall00ccbef2010-12-21 00:44:39 +00005838 FunctionType::ExtInfo EI;
5839 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5840
5841 bool Variadic = (TypeStr[0] == '.');
5842
5843 // We really shouldn't be making a no-proto type here, especially in C++.
5844 if (ArgTypes.empty() && Variadic)
5845 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005846
John McCalle23cf432010-12-14 08:05:40 +00005847 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00005848 EPI.ExtInfo = EI;
5849 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00005850
5851 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00005852}
Eli Friedmana95d7572009-08-19 07:44:53 +00005853
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005854GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5855 GVALinkage External = GVA_StrongExternal;
5856
5857 Linkage L = FD->getLinkage();
5858 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5859 FD->getType()->getLinkage() == UniqueExternalLinkage)
5860 L = UniqueExternalLinkage;
5861
5862 switch (L) {
5863 case NoLinkage:
5864 case InternalLinkage:
5865 case UniqueExternalLinkage:
5866 return GVA_Internal;
5867
5868 case ExternalLinkage:
5869 switch (FD->getTemplateSpecializationKind()) {
5870 case TSK_Undeclared:
5871 case TSK_ExplicitSpecialization:
5872 External = GVA_StrongExternal;
5873 break;
5874
5875 case TSK_ExplicitInstantiationDefinition:
5876 return GVA_ExplicitTemplateInstantiation;
5877
5878 case TSK_ExplicitInstantiationDeclaration:
5879 case TSK_ImplicitInstantiation:
5880 External = GVA_TemplateInstantiation;
5881 break;
5882 }
5883 }
5884
5885 if (!FD->isInlined())
5886 return External;
5887
5888 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5889 // GNU or C99 inline semantics. Determine whether this symbol should be
5890 // externally visible.
5891 if (FD->isInlineDefinitionExternallyVisible())
5892 return External;
5893
5894 // C99 inline semantics, where the symbol is not externally visible.
5895 return GVA_C99Inline;
5896 }
5897
5898 // C++0x [temp.explicit]p9:
5899 // [ Note: The intent is that an inline function that is the subject of
5900 // an explicit instantiation declaration will still be implicitly
5901 // instantiated when used so that the body can be considered for
5902 // inlining, but that no out-of-line copy of the inline function would be
5903 // generated in the translation unit. -- end note ]
5904 if (FD->getTemplateSpecializationKind()
5905 == TSK_ExplicitInstantiationDeclaration)
5906 return GVA_C99Inline;
5907
5908 return GVA_CXXInline;
5909}
5910
5911GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5912 // If this is a static data member, compute the kind of template
5913 // specialization. Otherwise, this variable is not part of a
5914 // template.
5915 TemplateSpecializationKind TSK = TSK_Undeclared;
5916 if (VD->isStaticDataMember())
5917 TSK = VD->getTemplateSpecializationKind();
5918
5919 Linkage L = VD->getLinkage();
5920 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5921 VD->getType()->getLinkage() == UniqueExternalLinkage)
5922 L = UniqueExternalLinkage;
5923
5924 switch (L) {
5925 case NoLinkage:
5926 case InternalLinkage:
5927 case UniqueExternalLinkage:
5928 return GVA_Internal;
5929
5930 case ExternalLinkage:
5931 switch (TSK) {
5932 case TSK_Undeclared:
5933 case TSK_ExplicitSpecialization:
5934 return GVA_StrongExternal;
5935
5936 case TSK_ExplicitInstantiationDeclaration:
5937 llvm_unreachable("Variable should not be instantiated");
5938 // Fall through to treat this like any other instantiation.
5939
5940 case TSK_ExplicitInstantiationDefinition:
5941 return GVA_ExplicitTemplateInstantiation;
5942
5943 case TSK_ImplicitInstantiation:
5944 return GVA_TemplateInstantiation;
5945 }
5946 }
5947
5948 return GVA_StrongExternal;
5949}
5950
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005951bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005952 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5953 if (!VD->isFileVarDecl())
5954 return false;
5955 } else if (!isa<FunctionDecl>(D))
5956 return false;
5957
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005958 // Weak references don't produce any output by themselves.
5959 if (D->hasAttr<WeakRefAttr>())
5960 return false;
5961
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005962 // Aliases and used decls are required.
5963 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5964 return true;
5965
5966 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5967 // Forward declarations aren't required.
5968 if (!FD->isThisDeclarationADefinition())
5969 return false;
5970
5971 // Constructors and destructors are required.
5972 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5973 return true;
5974
5975 // The key function for a class is required.
5976 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5977 const CXXRecordDecl *RD = MD->getParent();
5978 if (MD->isOutOfLine() && RD->isDynamicClass()) {
5979 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
5980 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
5981 return true;
5982 }
5983 }
5984
5985 GVALinkage Linkage = GetGVALinkageForFunction(FD);
5986
5987 // static, static inline, always_inline, and extern inline functions can
5988 // always be deferred. Normal inline functions can be deferred in C99/C++.
5989 // Implicit template instantiations can also be deferred in C++.
5990 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
5991 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5992 return false;
5993 return true;
5994 }
5995
5996 const VarDecl *VD = cast<VarDecl>(D);
5997 assert(VD->isFileVarDecl() && "Expected file scoped var");
5998
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005999 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6000 return false;
6001
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006002 // Structs that have non-trivial constructors or destructors are required.
6003
6004 // FIXME: Handle references.
6005 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6006 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00006007 if (RD->hasDefinition() &&
6008 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006009 return true;
6010 }
6011 }
6012
6013 GVALinkage L = GetGVALinkageForVariable(VD);
6014 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6015 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6016 return false;
6017 }
6018
6019 return true;
6020}
Charles Davis071cc7d2010-08-16 03:33:14 +00006021
Charles Davisee743f92010-11-09 18:04:24 +00006022CallingConv ASTContext::getDefaultMethodCallConv() {
6023 // Pass through to the C++ ABI object
6024 return ABI->getDefaultMethodCallConv();
6025}
6026
Jay Foad4ba2a172011-01-12 09:06:06 +00006027bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006028 // Pass through to the C++ ABI object
6029 return ABI->isNearlyEmpty(RD);
6030}
6031
Peter Collingbourne14110472011-01-13 18:57:25 +00006032MangleContext *ASTContext::createMangleContext() {
6033 switch (Target.getCXXABI()) {
6034 case CXXABI_ARM:
6035 case CXXABI_Itanium:
6036 return createItaniumMangleContext(*this, getDiagnostics());
6037 case CXXABI_Microsoft:
6038 return createMicrosoftMangleContext(*this, getDiagnostics());
6039 }
6040 assert(0 && "Unsupported ABI");
6041 return 0;
6042}
6043
Charles Davis071cc7d2010-08-16 03:33:14 +00006044CXXABI::~CXXABI() {}