blob: 9fb2dc1a94030f3ee74095f8ca48dd456c319990 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000035#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000036
Chris Lattnerddc135e2006-11-10 06:34:16 +000037using namespace clang;
38
Douglas Gregor9672f922010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Steve Naroff0af91202007-04-27 21:51:21 +000052enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000054};
55
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000056const RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
57 if (!CommentsLoaded && ExternalSource) {
58 ExternalSource->ReadComments();
59 CommentsLoaded = true;
60 }
61
62 assert(D);
63
64 // TODO: handle comments for function parameters properly.
65 if (isa<ParmVarDecl>(D))
66 return NULL;
67
68 ArrayRef<RawComment> RawComments = Comments.getComments();
69
70 // If there are no comments anywhere, we won't find anything.
71 if (RawComments.empty())
72 return NULL;
73
74 // If the declaration doesn't map directly to a location in a file, we
75 // can't find the comment.
76 SourceLocation DeclLoc = D->getLocation();
77 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
78 return NULL;
79
80 // Find the comment that occurs just after this declaration.
81 ArrayRef<RawComment>::iterator Comment
82 = std::lower_bound(RawComments.begin(),
83 RawComments.end(),
Dmitri Gribenkofecc2e02012-06-21 21:02:45 +000084 RawComment(SourceMgr, SourceRange(DeclLoc)),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000085 BeforeThanCompare<RawComment>(SourceMgr));
86
87 // Decompose the location for the declaration and find the beginning of the
88 // file buffer.
89 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
90
91 // First check whether we have a trailing comment.
92 if (Comment != RawComments.end() &&
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +000093 Comment->isDocumentation() && Comment->isTrailingComment() &&
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000094 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) {
95 std::pair<FileID, unsigned> CommentBeginDecomp
96 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getBegin());
97 // Check that Doxygen trailing comment comes after the declaration, starts
98 // on the same line and in the same file as the declaration.
99 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
100 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
101 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
102 CommentBeginDecomp.second)) {
103 return &*Comment;
104 }
105 }
106
107 // The comment just after the declaration was not a trailing comment.
108 // Let's look at the previous comment.
109 if (Comment == RawComments.begin())
110 return NULL;
111 --Comment;
112
113 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000114 if (!Comment->isDocumentation() || Comment->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000115 return NULL;
116
117 // Decompose the end of the comment.
118 std::pair<FileID, unsigned> CommentEndDecomp
119 = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getEnd());
120
121 // If the comment and the declaration aren't in the same file, then they
122 // aren't related.
123 if (DeclLocDecomp.first != CommentEndDecomp.first)
124 return NULL;
125
126 // Get the corresponding buffer.
127 bool Invalid = false;
128 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
129 &Invalid).data();
130 if (Invalid)
131 return NULL;
132
133 // Extract text between the comment and declaration.
134 StringRef Text(Buffer + CommentEndDecomp.second,
135 DeclLocDecomp.second - CommentEndDecomp.second);
136
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000137 // There should be no other declarations or preprocessor directives between
138 // comment and declaration.
139 if (Text.find_first_of(",;{}#") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000140 return NULL;
141
142 return &*Comment;
143}
144
145const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
146 // Check whether we have cached a comment string for this declaration
147 // already.
148 llvm::DenseMap<const Decl *, const RawComment *>::iterator Pos
149 = DeclComments.find(D);
150 if (Pos != DeclComments.end())
151 return Pos->second;
152
153 const RawComment *RC = getRawCommentForDeclNoCache(D);
154 DeclComments[D] = RC;
155 return RC;
156}
157
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000158void
159ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
160 TemplateTemplateParmDecl *Parm) {
161 ID.AddInteger(Parm->getDepth());
162 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000163 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000164
165 TemplateParameterList *Params = Parm->getTemplateParameters();
166 ID.AddInteger(Params->size());
167 for (TemplateParameterList::const_iterator P = Params->begin(),
168 PEnd = Params->end();
169 P != PEnd; ++P) {
170 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
171 ID.AddInteger(0);
172 ID.AddBoolean(TTP->isParameterPack());
173 continue;
174 }
175
176 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
177 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000178 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000179 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000180 if (NTTP->isExpandedParameterPack()) {
181 ID.AddBoolean(true);
182 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000183 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
184 QualType T = NTTP->getExpansionType(I);
185 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
186 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000187 } else
188 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000189 continue;
190 }
191
192 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
193 ID.AddInteger(2);
194 Profile(ID, TTP);
195 }
196}
197
198TemplateTemplateParmDecl *
199ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000200 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000201 // Check if we already have a canonical template template parameter.
202 llvm::FoldingSetNodeID ID;
203 CanonicalTemplateTemplateParm::Profile(ID, TTP);
204 void *InsertPos = 0;
205 CanonicalTemplateTemplateParm *Canonical
206 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
207 if (Canonical)
208 return Canonical->getParam();
209
210 // Build a canonical template parameter list.
211 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000212 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000213 CanonParams.reserve(Params->size());
214 for (TemplateParameterList::const_iterator P = Params->begin(),
215 PEnd = Params->end();
216 P != PEnd; ++P) {
217 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
218 CanonParams.push_back(
219 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000220 SourceLocation(),
221 SourceLocation(),
222 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000223 TTP->getIndex(), 0, false,
224 TTP->isParameterPack()));
225 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000226 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
227 QualType T = getCanonicalType(NTTP->getType());
228 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
229 NonTypeTemplateParmDecl *Param;
230 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000231 SmallVector<QualType, 2> ExpandedTypes;
232 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000233 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
234 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
235 ExpandedTInfos.push_back(
236 getTrivialTypeSourceInfo(ExpandedTypes.back()));
237 }
238
239 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000240 SourceLocation(),
241 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000242 NTTP->getDepth(),
243 NTTP->getPosition(), 0,
244 T,
245 TInfo,
246 ExpandedTypes.data(),
247 ExpandedTypes.size(),
248 ExpandedTInfos.data());
249 } else {
250 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000251 SourceLocation(),
252 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000253 NTTP->getDepth(),
254 NTTP->getPosition(), 0,
255 T,
256 NTTP->isParameterPack(),
257 TInfo);
258 }
259 CanonParams.push_back(Param);
260
261 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000262 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
263 cast<TemplateTemplateParmDecl>(*P)));
264 }
265
266 TemplateTemplateParmDecl *CanonTTP
267 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
268 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000269 TTP->getPosition(),
270 TTP->isParameterPack(),
271 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000272 TemplateParameterList::Create(*this, SourceLocation(),
273 SourceLocation(),
274 CanonParams.data(),
275 CanonParams.size(),
276 SourceLocation()));
277
278 // Get the new insert position for the node we care about.
279 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
280 assert(Canonical == 0 && "Shouldn't be in the map!");
281 (void)Canonical;
282
283 // Create the canonical template template parameter entry.
284 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
285 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
286 return CanonTTP;
287}
288
Charles Davis53c59df2010-08-16 03:33:14 +0000289CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000290 if (!LangOpts.CPlusPlus) return 0;
291
Charles Davis6bcb07a2010-08-19 02:18:14 +0000292 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000293 case CXXABI_ARM:
294 return CreateARMCXXABI(*this);
295 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000296 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000297 case CXXABI_Microsoft:
298 return CreateMicrosoftCXXABI(*this);
299 }
David Blaikie8a40f702012-01-17 06:56:22 +0000300 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000301}
302
Douglas Gregore8bbc122011-09-02 00:18:52 +0000303static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000304 const LangOptions &LOpts) {
305 if (LOpts.FakeAddressSpaceMap) {
306 // The fake address space map must have a distinct entry for each
307 // language-specific address space.
308 static const unsigned FakeAddrSpaceMap[] = {
309 1, // opencl_global
310 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000311 3, // opencl_constant
312 4, // cuda_device
313 5, // cuda_constant
314 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000315 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000316 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000317 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000318 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000319 }
320}
321
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000322ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000323 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000324 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000325 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000326 unsigned size_reserve,
327 bool DelayInitialization)
328 : FunctionProtoTypes(this_()),
329 TemplateSpecializationTypes(this_()),
330 DependentTemplateSpecializationTypes(this_()),
331 SubstTemplateTemplateParmPacks(this_()),
332 GlobalNestedNameSpecifier(0),
333 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000334 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000335 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000336 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000337 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000338 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
339 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
340 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000341 NullTypeSourceInfo(QualType()),
342 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000343 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000344 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000345 Idents(idents), Selectors(sels),
346 BuiltinInfo(builtins),
347 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000348 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000349 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000350 LastSDM(0, 0),
351 UniqueBlockByRefTypeID(0)
352{
Mike Stump11289f42009-09-09 15:08:12 +0000353 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000354 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000355
356 if (!DelayInitialization) {
357 assert(t && "No target supplied for ASTContext initialization");
358 InitBuiltinTypes(*t);
359 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000360}
361
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000362ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000363 // Release the DenseMaps associated with DeclContext objects.
364 // FIXME: Is this the ideal solution?
365 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000366
Douglas Gregor5b11d492010-07-25 17:53:33 +0000367 // Call all of the deallocation functions.
368 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
369 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000370
Ted Kremenek076baeb2010-06-08 23:00:58 +0000371 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000372 // because they can contain DenseMaps.
373 for (llvm::DenseMap<const ObjCContainerDecl*,
374 const ASTRecordLayout*>::iterator
375 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
376 // Increment in loop to prevent using deallocated memory.
377 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
378 R->Destroy(*this);
379
Ted Kremenek076baeb2010-06-08 23:00:58 +0000380 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
381 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
382 // Increment in loop to prevent using deallocated memory.
383 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
384 R->Destroy(*this);
385 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000386
387 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
388 AEnd = DeclAttrs.end();
389 A != AEnd; ++A)
390 A->second->~AttrVec();
391}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000392
Douglas Gregor1a809332010-05-23 18:26:36 +0000393void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
394 Deallocations.push_back(std::make_pair(Callback, Data));
395}
396
Mike Stump11289f42009-09-09 15:08:12 +0000397void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000398ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000399 ExternalSource.reset(Source.take());
400}
401
Chris Lattner4eb445d2007-01-26 01:27:23 +0000402void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000403 llvm::errs() << "\n*** AST Context Stats:\n";
404 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000405
Douglas Gregora30d0462009-05-26 14:40:08 +0000406 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000407#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000408#define ABSTRACT_TYPE(Name, Parent)
409#include "clang/AST/TypeNodes.def"
410 0 // Extra
411 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000412
Chris Lattner4eb445d2007-01-26 01:27:23 +0000413 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
414 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000415 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000416 }
417
Douglas Gregora30d0462009-05-26 14:40:08 +0000418 unsigned Idx = 0;
419 unsigned TotalBytes = 0;
420#define TYPE(Name, Parent) \
421 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000422 llvm::errs() << " " << counts[Idx] << " " << #Name \
423 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000424 TotalBytes += counts[Idx] * sizeof(Name##Type); \
425 ++Idx;
426#define ABSTRACT_TYPE(Name, Parent)
427#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chandler Carruth3c147a72011-07-04 05:32:14 +0000429 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
430
Douglas Gregor7454c562010-07-02 20:37:36 +0000431 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000432 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
433 << NumImplicitDefaultConstructors
434 << " implicit default constructors created\n";
435 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
436 << NumImplicitCopyConstructors
437 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000438 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000439 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
440 << NumImplicitMoveConstructors
441 << " implicit move constructors created\n";
442 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
443 << NumImplicitCopyAssignmentOperators
444 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000445 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000446 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
447 << NumImplicitMoveAssignmentOperators
448 << " implicit move assignment operators created\n";
449 llvm::errs() << NumImplicitDestructorsDeclared << "/"
450 << NumImplicitDestructors
451 << " implicit destructors created\n";
452
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000453 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000454 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000455 ExternalSource->PrintStats();
456 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000457
Douglas Gregor5b11d492010-07-25 17:53:33 +0000458 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000459}
460
Douglas Gregor801c99d2011-08-12 06:49:56 +0000461TypedefDecl *ASTContext::getInt128Decl() const {
462 if (!Int128Decl) {
463 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
464 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
465 getTranslationUnitDecl(),
466 SourceLocation(),
467 SourceLocation(),
468 &Idents.get("__int128_t"),
469 TInfo);
470 }
471
472 return Int128Decl;
473}
474
475TypedefDecl *ASTContext::getUInt128Decl() const {
476 if (!UInt128Decl) {
477 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
478 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
479 getTranslationUnitDecl(),
480 SourceLocation(),
481 SourceLocation(),
482 &Idents.get("__uint128_t"),
483 TInfo);
484 }
485
486 return UInt128Decl;
487}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000488
John McCall48f2d582009-10-23 23:03:21 +0000489void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000490 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000491 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000492 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000493}
494
Douglas Gregore8bbc122011-09-02 00:18:52 +0000495void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
496 assert((!this->Target || this->Target == &Target) &&
497 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000498 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000499
Douglas Gregore8bbc122011-09-02 00:18:52 +0000500 this->Target = &Target;
501
502 ABI.reset(createCXXABI(Target));
503 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
504
Chris Lattner970e54e2006-11-12 00:37:36 +0000505 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000506 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000507
Chris Lattner970e54e2006-11-12 00:37:36 +0000508 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000509 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000510 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000511 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000512 InitBuiltinType(CharTy, BuiltinType::Char_S);
513 else
514 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000515 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000516 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
517 InitBuiltinType(ShortTy, BuiltinType::Short);
518 InitBuiltinType(IntTy, BuiltinType::Int);
519 InitBuiltinType(LongTy, BuiltinType::Long);
520 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000521
Chris Lattner970e54e2006-11-12 00:37:36 +0000522 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000523 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
524 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
525 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
526 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
527 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattner970e54e2006-11-12 00:37:36 +0000529 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000530 InitBuiltinType(FloatTy, BuiltinType::Float);
531 InitBuiltinType(DoubleTy, BuiltinType::Double);
532 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000533
Chris Lattnerf122cef2009-04-30 02:43:43 +0000534 // GNU extension, 128-bit integers.
535 InitBuiltinType(Int128Ty, BuiltinType::Int128);
536 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
537
Chris Lattnerad3467e2010-12-25 23:25:43 +0000538 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000539 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000540 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
541 else // -fshort-wchar makes wchar_t be unsigned.
542 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
543 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000544 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000545
James Molloy36365542012-05-04 10:55:22 +0000546 WIntTy = getFromTargetType(Target.getWIntType());
547
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000548 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
549 InitBuiltinType(Char16Ty, BuiltinType::Char16);
550 else // C99
551 Char16Ty = getFromTargetType(Target.getChar16Type());
552
553 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
554 InitBuiltinType(Char32Ty, BuiltinType::Char32);
555 else // C99
556 Char32Ty = getFromTargetType(Target.getChar32Type());
557
Douglas Gregor4619e432008-12-05 23:32:09 +0000558 // Placeholder type for type-dependent expressions whose type is
559 // completely unknown. No code should ever check a type against
560 // DependentTy and users should never see it; however, it is here to
561 // help diagnose failures to properly check for type-dependent
562 // expressions.
563 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000564
John McCall36e7fe32010-10-12 00:20:44 +0000565 // Placeholder type for functions.
566 InitBuiltinType(OverloadTy, BuiltinType::Overload);
567
John McCall0009fcc2011-04-26 20:42:42 +0000568 // Placeholder type for bound members.
569 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
570
John McCall526ab472011-10-25 17:37:35 +0000571 // Placeholder type for pseudo-objects.
572 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
573
John McCall31996342011-04-07 08:22:57 +0000574 // "any" type; useful for debugger-like clients.
575 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
576
John McCall8a6b59a2011-10-17 18:09:15 +0000577 // Placeholder type for unbridged ARC casts.
578 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
579
Chris Lattner970e54e2006-11-12 00:37:36 +0000580 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000581 FloatComplexTy = getComplexType(FloatTy);
582 DoubleComplexTy = getComplexType(DoubleTy);
583 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000584
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000585 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000586 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
587 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000588 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000589
590 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000591 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
592 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000593
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000594 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000595
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000596 // void * type
597 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000598
599 // nullptr type (C++0x 2.14.7)
600 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000601
602 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
603 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000604}
605
David Blaikie9c902b52011-09-25 23:23:43 +0000606DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000607 return SourceMgr.getDiagnostics();
608}
609
Douglas Gregor561eceb2010-08-30 16:49:28 +0000610AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
611 AttrVec *&Result = DeclAttrs[D];
612 if (!Result) {
613 void *Mem = Allocate(sizeof(AttrVec));
614 Result = new (Mem) AttrVec;
615 }
616
617 return *Result;
618}
619
620/// \brief Erase the attributes corresponding to the given declaration.
621void ASTContext::eraseDeclAttrs(const Decl *D) {
622 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
623 if (Pos != DeclAttrs.end()) {
624 Pos->second->~AttrVec();
625 DeclAttrs.erase(Pos);
626 }
627}
628
Douglas Gregor86d142a2009-10-08 07:24:58 +0000629MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000630ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000631 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000632 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000633 = InstantiatedFromStaticDataMember.find(Var);
634 if (Pos == InstantiatedFromStaticDataMember.end())
635 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000636
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000637 return Pos->second;
638}
639
Mike Stump11289f42009-09-09 15:08:12 +0000640void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000641ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000642 TemplateSpecializationKind TSK,
643 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000644 assert(Inst->isStaticDataMember() && "Not a static data member");
645 assert(Tmpl->isStaticDataMember() && "Not a static data member");
646 assert(!InstantiatedFromStaticDataMember[Inst] &&
647 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000648 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000649 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000650}
651
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000652FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
653 const FunctionDecl *FD){
654 assert(FD && "Specialization is 0");
655 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000656 = ClassScopeSpecializationPattern.find(FD);
657 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000658 return 0;
659
660 return Pos->second;
661}
662
663void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
664 FunctionDecl *Pattern) {
665 assert(FD && "Specialization is 0");
666 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000667 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000668}
669
John McCalle61f2ba2009-11-18 02:36:19 +0000670NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000671ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000672 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000673 = InstantiatedFromUsingDecl.find(UUD);
674 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000675 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000676
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000677 return Pos->second;
678}
679
680void
John McCallb96ec562009-12-04 22:46:56 +0000681ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
682 assert((isa<UsingDecl>(Pattern) ||
683 isa<UnresolvedUsingValueDecl>(Pattern) ||
684 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
685 "pattern decl is not a using decl");
686 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
687 InstantiatedFromUsingDecl[Inst] = Pattern;
688}
689
690UsingShadowDecl *
691ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
692 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
693 = InstantiatedFromUsingShadowDecl.find(Inst);
694 if (Pos == InstantiatedFromUsingShadowDecl.end())
695 return 0;
696
697 return Pos->second;
698}
699
700void
701ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
702 UsingShadowDecl *Pattern) {
703 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
704 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000705}
706
Anders Carlsson5da84842009-09-01 04:26:58 +0000707FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
708 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
709 = InstantiatedFromUnnamedFieldDecl.find(Field);
710 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
711 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000712
Anders Carlsson5da84842009-09-01 04:26:58 +0000713 return Pos->second;
714}
715
716void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
717 FieldDecl *Tmpl) {
718 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
719 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
720 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
721 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000722
Anders Carlsson5da84842009-09-01 04:26:58 +0000723 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
724}
725
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000726bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
727 const FieldDecl *LastFD) const {
728 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000729 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000730}
731
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000732bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
733 const FieldDecl *LastFD) const {
734 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000735 FD->getBitWidthValue(*this) == 0 &&
736 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000737}
738
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000739bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
740 const FieldDecl *LastFD) const {
741 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000742 FD->getBitWidthValue(*this) &&
743 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000744}
745
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000746bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000747 const FieldDecl *LastFD) const {
748 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000749 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000750}
751
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000752bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000753 const FieldDecl *LastFD) const {
754 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000755 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000756}
757
Douglas Gregor832940b2010-03-02 23:58:15 +0000758ASTContext::overridden_cxx_method_iterator
759ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
760 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
761 = OverriddenMethods.find(Method);
762 if (Pos == OverriddenMethods.end())
763 return 0;
764
765 return Pos->second.begin();
766}
767
768ASTContext::overridden_cxx_method_iterator
769ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
770 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
771 = OverriddenMethods.find(Method);
772 if (Pos == OverriddenMethods.end())
773 return 0;
774
775 return Pos->second.end();
776}
777
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000778unsigned
779ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
780 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
781 = OverriddenMethods.find(Method);
782 if (Pos == OverriddenMethods.end())
783 return 0;
784
785 return Pos->second.size();
786}
787
Douglas Gregor832940b2010-03-02 23:58:15 +0000788void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
789 const CXXMethodDecl *Overridden) {
790 OverriddenMethods[Method].push_back(Overridden);
791}
792
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000793void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
794 assert(!Import->NextLocalImport && "Import declaration already in the chain");
795 assert(!Import->isFromASTFile() && "Non-local import declaration");
796 if (!FirstLocalImport) {
797 FirstLocalImport = Import;
798 LastLocalImport = Import;
799 return;
800 }
801
802 LastLocalImport->NextLocalImport = Import;
803 LastLocalImport = Import;
804}
805
Chris Lattner53cfe802007-07-18 17:52:12 +0000806//===----------------------------------------------------------------------===//
807// Type Sizing and Analysis
808//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000809
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000810/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
811/// scalar floating point type.
812const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000813 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000814 assert(BT && "Not a floating point type!");
815 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000816 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000817 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000818 case BuiltinType::Float: return Target->getFloatFormat();
819 case BuiltinType::Double: return Target->getDoubleFormat();
820 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000821 }
822}
823
Ken Dyck160146e2010-01-27 17:10:57 +0000824/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000825/// specified decl. Note that bitfields do not have a valid alignment, so
826/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000827/// If @p RefAsPointee, references are treated like their underlying type
828/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000829CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000830 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000831
John McCall94268702010-10-08 18:24:19 +0000832 bool UseAlignAttrOnly = false;
833 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
834 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000835
John McCall94268702010-10-08 18:24:19 +0000836 // __attribute__((aligned)) can increase or decrease alignment
837 // *except* on a struct or struct member, where it only increases
838 // alignment unless 'packed' is also specified.
839 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000840 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000841 // ignore that possibility; Sema should diagnose it.
842 if (isa<FieldDecl>(D)) {
843 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
844 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
845 } else {
846 UseAlignAttrOnly = true;
847 }
848 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000849 else if (isa<FieldDecl>(D))
850 UseAlignAttrOnly =
851 D->hasAttr<PackedAttr>() ||
852 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000853
John McCall4e819612011-01-20 07:57:12 +0000854 // If we're using the align attribute only, just ignore everything
855 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000856 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000857 // do nothing
858
John McCall94268702010-10-08 18:24:19 +0000859 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000860 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000861 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000862 if (RefAsPointee)
863 T = RT->getPointeeType();
864 else
865 T = getPointerType(RT->getPointeeType());
866 }
867 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000868 // Adjust alignments of declarations with array type by the
869 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000870 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000871 const ArrayType *arrayType;
872 if (MinWidth && (arrayType = getAsArrayType(T))) {
873 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000874 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000875 else if (isa<ConstantArrayType>(arrayType) &&
876 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000877 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000878
John McCall33ddac02011-01-19 10:06:00 +0000879 // Walk through any array types while we're at it.
880 T = getBaseElementType(arrayType);
881 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000882 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000883 }
John McCall4e819612011-01-20 07:57:12 +0000884
885 // Fields can be subject to extra alignment constraints, like if
886 // the field is packed, the struct is packed, or the struct has a
887 // a max-field-alignment constraint (#pragma pack). So calculate
888 // the actual alignment of the field within the struct, and then
889 // (as we're expected to) constrain that by the alignment of the type.
890 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
891 // So calculate the alignment of the field.
892 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
893
894 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000895 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000896
897 // Use the GCD of that and the offset within the record.
898 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
899 if (offset > 0) {
900 // Alignment is always a power of 2, so the GCD will be a power of 2,
901 // which means we get to do this crazy thing instead of Euclid's.
902 uint64_t lowBitOfOffset = offset & (~offset + 1);
903 if (lowBitOfOffset < fieldAlign)
904 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
905 }
906
907 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000908 }
Chris Lattner68061312009-01-24 21:53:27 +0000909 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000910
Ken Dyckcc56c542011-01-15 18:38:59 +0000911 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000912}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000913
John McCall87fe5d52010-05-20 01:18:31 +0000914std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000915ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000916 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000917 return std::make_pair(toCharUnitsFromBits(Info.first),
918 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000919}
920
921std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000922ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000923 return getTypeInfoInChars(T.getTypePtr());
924}
925
Daniel Dunbarc6475872012-03-09 04:12:54 +0000926std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
927 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
928 if (it != MemoizedTypeInfo.end())
929 return it->second;
930
931 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
932 MemoizedTypeInfo.insert(std::make_pair(T, Info));
933 return Info;
934}
935
936/// getTypeInfoImpl - Return the size of the specified type, in bits. This
937/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000938///
939/// FIXME: Pointers into different addr spaces could have different sizes and
940/// alignment requirements: getPointerInfo should take an AddrSpace, this
941/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000942std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000943ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000944 uint64_t Width=0;
945 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000946 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000947#define TYPE(Class, Base)
948#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000949#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000950#define DEPENDENT_TYPE(Class, Base) case Type::Class:
951#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000952 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000953
Chris Lattner355332d2007-07-13 22:27:08 +0000954 case Type::FunctionNoProto:
955 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000956 // GCC extension: alignof(function) = 32 bits
957 Width = 0;
958 Align = 32;
959 break;
960
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000961 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000962 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000963 Width = 0;
964 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
965 break;
966
Steve Naroff5c131802007-08-30 01:06:46 +0000967 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000968 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000969
Chris Lattner37e05872008-03-05 18:54:05 +0000970 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000971 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +0000972 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
973 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000974 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000975 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000976 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000977 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000978 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000979 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000980 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000981 const VectorType *VT = cast<VectorType>(T);
982 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
983 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000984 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000985 // If the alignment is not a power of 2, round up to the next power of 2.
986 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000987 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000988 Align = llvm::NextPowerOf2(Align);
989 Width = llvm::RoundUpToAlignment(Width, Align);
990 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000991 break;
992 }
Chris Lattner647fb222007-07-18 18:26:58 +0000993
Chris Lattner7570e9c2008-03-08 08:52:55 +0000994 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000995 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000996 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000997 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000998 // GCC extension: alignof(void) = 8 bits.
999 Width = 0;
1000 Align = 8;
1001 break;
1002
Chris Lattner6a4f7452007-12-19 19:23:28 +00001003 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001004 Width = Target->getBoolWidth();
1005 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001006 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001007 case BuiltinType::Char_S:
1008 case BuiltinType::Char_U:
1009 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001010 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001011 Width = Target->getCharWidth();
1012 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001013 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001014 case BuiltinType::WChar_S:
1015 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001016 Width = Target->getWCharWidth();
1017 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001018 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001019 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001020 Width = Target->getChar16Width();
1021 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001022 break;
1023 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001024 Width = Target->getChar32Width();
1025 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001026 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001027 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001028 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001029 Width = Target->getShortWidth();
1030 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001031 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001032 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001033 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001034 Width = Target->getIntWidth();
1035 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001036 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001037 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001038 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001039 Width = Target->getLongWidth();
1040 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001041 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001042 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001043 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001044 Width = Target->getLongLongWidth();
1045 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001046 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001047 case BuiltinType::Int128:
1048 case BuiltinType::UInt128:
1049 Width = 128;
1050 Align = 128; // int128_t is 128-bit aligned on all targets.
1051 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001052 case BuiltinType::Half:
1053 Width = Target->getHalfWidth();
1054 Align = Target->getHalfAlign();
1055 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001056 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001057 Width = Target->getFloatWidth();
1058 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001059 break;
1060 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001061 Width = Target->getDoubleWidth();
1062 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001063 break;
1064 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001065 Width = Target->getLongDoubleWidth();
1066 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001067 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001068 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001069 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1070 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001071 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001072 case BuiltinType::ObjCId:
1073 case BuiltinType::ObjCClass:
1074 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001075 Width = Target->getPointerWidth(0);
1076 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001077 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001078 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001079 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001080 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001081 Width = Target->getPointerWidth(0);
1082 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001083 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001084 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001085 unsigned AS = getTargetAddressSpace(
1086 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001087 Width = Target->getPointerWidth(AS);
1088 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001089 break;
1090 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001091 case Type::LValueReference:
1092 case Type::RValueReference: {
1093 // alignof and sizeof should never enter this code path here, so we go
1094 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001095 unsigned AS = getTargetAddressSpace(
1096 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001097 Width = Target->getPointerWidth(AS);
1098 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001099 break;
1100 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001101 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001102 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001103 Width = Target->getPointerWidth(AS);
1104 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001105 break;
1106 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001107 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001108 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001109 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001110 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001111 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001112 Align = PtrDiffInfo.second;
1113 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001114 }
Chris Lattner647fb222007-07-18 18:26:58 +00001115 case Type::Complex: {
1116 // Complex types have the same alignment as their elements, but twice the
1117 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001118 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001119 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001120 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001121 Align = EltInfo.second;
1122 break;
1123 }
John McCall8b07ec22010-05-15 11:32:37 +00001124 case Type::ObjCObject:
1125 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001126 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001127 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001128 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001129 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001130 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001131 break;
1132 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001133 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001134 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001135 const TagType *TT = cast<TagType>(T);
1136
1137 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001138 Width = 8;
1139 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001140 break;
1141 }
Mike Stump11289f42009-09-09 15:08:12 +00001142
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001143 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001144 return getTypeInfo(ET->getDecl()->getIntegerType());
1145
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001146 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001147 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001148 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001149 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001150 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001151 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001152
Chris Lattner63d2b362009-10-22 05:17:15 +00001153 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001154 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1155 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001156
Richard Smith30482bc2011-02-20 03:19:35 +00001157 case Type::Auto: {
1158 const AutoType *A = cast<AutoType>(T);
1159 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001160 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001161 }
1162
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001163 case Type::Paren:
1164 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1165
Douglas Gregoref462e62009-04-30 17:32:17 +00001166 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001167 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001168 std::pair<uint64_t, unsigned> Info
1169 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001170 // If the typedef has an aligned attribute on it, it overrides any computed
1171 // alignment we have. This violates the GCC documentation (which says that
1172 // attribute(aligned) can only round up) but matches its implementation.
1173 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1174 Align = AttrAlign;
1175 else
1176 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001177 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001178 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001179 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001180
1181 case Type::TypeOfExpr:
1182 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1183 .getTypePtr());
1184
1185 case Type::TypeOf:
1186 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1187
Anders Carlsson81df7b82009-06-24 19:06:50 +00001188 case Type::Decltype:
1189 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1190 .getTypePtr());
1191
Alexis Hunte852b102011-05-24 22:41:36 +00001192 case Type::UnaryTransform:
1193 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1194
Abramo Bagnara6150c882010-05-11 21:36:43 +00001195 case Type::Elaborated:
1196 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001197
John McCall81904512011-01-06 01:58:22 +00001198 case Type::Attributed:
1199 return getTypeInfo(
1200 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1201
Richard Smith3f1b5d02011-05-05 21:57:07 +00001202 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001203 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001204 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001205 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1206 // A type alias template specialization may refer to a typedef with the
1207 // aligned attribute on it.
1208 if (TST->isTypeAlias())
1209 return getTypeInfo(TST->getAliasedType().getTypePtr());
1210 else
1211 return getTypeInfo(getCanonicalType(T));
1212 }
1213
Eli Friedman0dfb8892011-10-06 23:00:33 +00001214 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001215 std::pair<uint64_t, unsigned> Info
1216 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1217 Width = Info.first;
1218 Align = Info.second;
1219 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1220 llvm::isPowerOf2_64(Width)) {
1221 // We can potentially perform lock-free atomic operations for this
1222 // type; promote the alignment appropriately.
1223 // FIXME: We could potentially promote the width here as well...
1224 // is that worthwhile? (Non-struct atomic types generally have
1225 // power-of-two size anyway, but structs might not. Requires a bit
1226 // of implementation work to make sure we zero out the extra bits.)
1227 Align = static_cast<unsigned>(Width);
1228 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001229 }
1230
Douglas Gregoref462e62009-04-30 17:32:17 +00001231 }
Mike Stump11289f42009-09-09 15:08:12 +00001232
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001233 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001234 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001235}
1236
Ken Dyckcc56c542011-01-15 18:38:59 +00001237/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1238CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1239 return CharUnits::fromQuantity(BitSize / getCharWidth());
1240}
1241
Ken Dyckb0fcc592011-02-11 01:54:29 +00001242/// toBits - Convert a size in characters to a size in characters.
1243int64_t ASTContext::toBits(CharUnits CharSize) const {
1244 return CharSize.getQuantity() * getCharWidth();
1245}
1246
Ken Dyck8c89d592009-12-22 14:23:30 +00001247/// getTypeSizeInChars - Return the size of the specified type, in characters.
1248/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001249CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001250 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001251}
Jay Foad39c79802011-01-12 09:06:06 +00001252CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001253 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001254}
1255
Ken Dycka6046ab2010-01-26 17:25:18 +00001256/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001257/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001258CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001259 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001260}
Jay Foad39c79802011-01-12 09:06:06 +00001261CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001262 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001263}
1264
Chris Lattnera3402cd2009-01-27 18:08:34 +00001265/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1266/// type for the current target in bits. This can be different than the ABI
1267/// alignment in cases where it is beneficial for performance to overalign
1268/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001269unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001270 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001271
1272 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001273 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001274 T = CT->getElementType().getTypePtr();
1275 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001276 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1277 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001278 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1279
Chris Lattnera3402cd2009-01-27 18:08:34 +00001280 return ABIAlign;
1281}
1282
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001283/// DeepCollectObjCIvars -
1284/// This routine first collects all declared, but not synthesized, ivars in
1285/// super class and then collects all ivars, including those synthesized for
1286/// current class. This routine is used for implementation of current class
1287/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001288///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001289void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1290 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001291 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001292 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1293 DeepCollectObjCIvars(SuperClass, false, Ivars);
1294 if (!leafClass) {
1295 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1296 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001297 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001298 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001299 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001300 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001301 Iv= Iv->getNextIvar())
1302 Ivars.push_back(Iv);
1303 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001304}
1305
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001306/// CollectInheritedProtocols - Collect all protocols in current class and
1307/// those inherited by it.
1308void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001309 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001310 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001311 // We can use protocol_iterator here instead of
1312 // all_referenced_protocol_iterator since we are walking all categories.
1313 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1314 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001315 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001316 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001317 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001318 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001319 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001320 CollectInheritedProtocols(*P, Protocols);
1321 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001322 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001323
1324 // Categories of this Interface.
1325 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1326 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1327 CollectInheritedProtocols(CDeclChain, Protocols);
1328 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1329 while (SD) {
1330 CollectInheritedProtocols(SD, Protocols);
1331 SD = SD->getSuperClass();
1332 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001333 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001334 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001335 PE = OC->protocol_end(); P != PE; ++P) {
1336 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001337 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001338 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1339 PE = Proto->protocol_end(); P != PE; ++P)
1340 CollectInheritedProtocols(*P, Protocols);
1341 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001342 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001343 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1344 PE = OP->protocol_end(); P != PE; ++P) {
1345 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001346 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001347 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1348 PE = Proto->protocol_end(); P != PE; ++P)
1349 CollectInheritedProtocols(*P, Protocols);
1350 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001351 }
1352}
1353
Jay Foad39c79802011-01-12 09:06:06 +00001354unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001355 unsigned count = 0;
1356 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001357 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1358 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001359 count += CDecl->ivar_size();
1360
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001361 // Count ivar defined in this class's implementation. This
1362 // includes synthesized ivars.
1363 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001364 count += ImplDecl->ivar_size();
1365
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001366 return count;
1367}
1368
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001369bool ASTContext::isSentinelNullExpr(const Expr *E) {
1370 if (!E)
1371 return false;
1372
1373 // nullptr_t is always treated as null.
1374 if (E->getType()->isNullPtrType()) return true;
1375
1376 if (E->getType()->isAnyPointerType() &&
1377 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1378 Expr::NPC_ValueDependentIsNull))
1379 return true;
1380
1381 // Unfortunately, __null has type 'int'.
1382 if (isa<GNUNullExpr>(E)) return true;
1383
1384 return false;
1385}
1386
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001387/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1388ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1389 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1390 I = ObjCImpls.find(D);
1391 if (I != ObjCImpls.end())
1392 return cast<ObjCImplementationDecl>(I->second);
1393 return 0;
1394}
1395/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1396ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1397 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1398 I = ObjCImpls.find(D);
1399 if (I != ObjCImpls.end())
1400 return cast<ObjCCategoryImplDecl>(I->second);
1401 return 0;
1402}
1403
1404/// \brief Set the implementation of ObjCInterfaceDecl.
1405void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1406 ObjCImplementationDecl *ImplD) {
1407 assert(IFaceD && ImplD && "Passed null params");
1408 ObjCImpls[IFaceD] = ImplD;
1409}
1410/// \brief Set the implementation of ObjCCategoryDecl.
1411void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1412 ObjCCategoryImplDecl *ImplD) {
1413 assert(CatD && ImplD && "Passed null params");
1414 ObjCImpls[CatD] = ImplD;
1415}
1416
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001417ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1418 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1419 return ID;
1420 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1421 return CD->getClassInterface();
1422 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1423 return IMD->getClassInterface();
1424
1425 return 0;
1426}
1427
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001428/// \brief Get the copy initialization expression of VarDecl,or NULL if
1429/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001430Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001431 assert(VD && "Passed null params");
1432 assert(VD->hasAttr<BlocksAttr>() &&
1433 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001434 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001435 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001436 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1437}
1438
1439/// \brief Set the copy inialization expression of a block var decl.
1440void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1441 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001442 assert(VD->hasAttr<BlocksAttr>() &&
1443 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001444 BlockVarCopyInits[VD] = Init;
1445}
1446
John McCallbcd03502009-12-07 02:54:59 +00001447TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001448 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001449 if (!DataSize)
1450 DataSize = TypeLoc::getFullDataSizeForType(T);
1451 else
1452 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001453 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001454
John McCallbcd03502009-12-07 02:54:59 +00001455 TypeSourceInfo *TInfo =
1456 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1457 new (TInfo) TypeSourceInfo(T);
1458 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001459}
1460
John McCallbcd03502009-12-07 02:54:59 +00001461TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001462 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001463 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001464 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001465 return DI;
1466}
1467
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001468const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001469ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001470 return getObjCLayout(D, 0);
1471}
1472
1473const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001474ASTContext::getASTObjCImplementationLayout(
1475 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001476 return getObjCLayout(D->getClassInterface(), D);
1477}
1478
Chris Lattner983a8bb2007-07-13 22:13:22 +00001479//===----------------------------------------------------------------------===//
1480// Type creation/memoization methods
1481//===----------------------------------------------------------------------===//
1482
Jay Foad39c79802011-01-12 09:06:06 +00001483QualType
John McCall33ddac02011-01-19 10:06:00 +00001484ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1485 unsigned fastQuals = quals.getFastQualifiers();
1486 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001487
1488 // Check if we've already instantiated this type.
1489 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001490 ExtQuals::Profile(ID, baseType, quals);
1491 void *insertPos = 0;
1492 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1493 assert(eq->getQualifiers() == quals);
1494 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001495 }
1496
John McCall33ddac02011-01-19 10:06:00 +00001497 // If the base type is not canonical, make the appropriate canonical type.
1498 QualType canon;
1499 if (!baseType->isCanonicalUnqualified()) {
1500 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001501 canonSplit.Quals.addConsistentQualifiers(quals);
1502 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001503
1504 // Re-find the insert position.
1505 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1506 }
1507
1508 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1509 ExtQualNodes.InsertNode(eq, insertPos);
1510 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001511}
1512
Jay Foad39c79802011-01-12 09:06:06 +00001513QualType
1514ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001515 QualType CanT = getCanonicalType(T);
1516 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001517 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001518
John McCall8ccfcb52009-09-24 19:53:00 +00001519 // If we are composing extended qualifiers together, merge together
1520 // into one ExtQuals node.
1521 QualifierCollector Quals;
1522 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001523
John McCall8ccfcb52009-09-24 19:53:00 +00001524 // If this type already has an address space specified, it cannot get
1525 // another one.
1526 assert(!Quals.hasAddressSpace() &&
1527 "Type cannot be in multiple addr spaces!");
1528 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001529
John McCall8ccfcb52009-09-24 19:53:00 +00001530 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001531}
1532
Chris Lattnerd60183d2009-02-18 22:53:11 +00001533QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001534 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001535 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001536 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001537 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001538
John McCall53fa7142010-12-24 02:08:15 +00001539 if (const PointerType *ptr = T->getAs<PointerType>()) {
1540 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001541 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001542 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1543 return getPointerType(ResultType);
1544 }
1545 }
Mike Stump11289f42009-09-09 15:08:12 +00001546
John McCall8ccfcb52009-09-24 19:53:00 +00001547 // If we are composing extended qualifiers together, merge together
1548 // into one ExtQuals node.
1549 QualifierCollector Quals;
1550 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001551
John McCall8ccfcb52009-09-24 19:53:00 +00001552 // If this type already has an ObjCGC specified, it cannot get
1553 // another one.
1554 assert(!Quals.hasObjCGCAttr() &&
1555 "Type cannot have multiple ObjCGCs!");
1556 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001557
John McCall8ccfcb52009-09-24 19:53:00 +00001558 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001559}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001560
John McCall4f5019e2010-12-19 02:44:49 +00001561const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1562 FunctionType::ExtInfo Info) {
1563 if (T->getExtInfo() == Info)
1564 return T;
1565
1566 QualType Result;
1567 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1568 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1569 } else {
1570 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1571 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1572 EPI.ExtInfo = Info;
1573 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1574 FPT->getNumArgs(), EPI);
1575 }
1576
1577 return cast<FunctionType>(Result.getTypePtr());
1578}
1579
Chris Lattnerc6395932007-06-22 20:56:16 +00001580/// getComplexType - Return the uniqued reference to the type for a complex
1581/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001582QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001583 // Unique pointers, to guarantee there is only one pointer of a particular
1584 // structure.
1585 llvm::FoldingSetNodeID ID;
1586 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001587
Chris Lattnerc6395932007-06-22 20:56:16 +00001588 void *InsertPos = 0;
1589 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1590 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001591
Chris Lattnerc6395932007-06-22 20:56:16 +00001592 // If the pointee type isn't canonical, this won't be a canonical type either,
1593 // so fill in the canonical type field.
1594 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001595 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001596 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001597
Chris Lattnerc6395932007-06-22 20:56:16 +00001598 // Get the new insert position for the node we care about.
1599 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001600 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001601 }
John McCall90d1c2d2009-09-24 23:30:46 +00001602 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001603 Types.push_back(New);
1604 ComplexTypes.InsertNode(New, InsertPos);
1605 return QualType(New, 0);
1606}
1607
Chris Lattner970e54e2006-11-12 00:37:36 +00001608/// getPointerType - Return the uniqued reference to the type for a pointer to
1609/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001610QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001611 // Unique pointers, to guarantee there is only one pointer of a particular
1612 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001613 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001614 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001615
Chris Lattner67521df2007-01-27 01:29:36 +00001616 void *InsertPos = 0;
1617 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001618 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001619
Chris Lattner7ccecb92006-11-12 08:50:50 +00001620 // If the pointee type isn't canonical, this won't be a canonical type either,
1621 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001622 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001623 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001624 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001625
Chris Lattner67521df2007-01-27 01:29:36 +00001626 // Get the new insert position for the node we care about.
1627 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001628 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001629 }
John McCall90d1c2d2009-09-24 23:30:46 +00001630 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001631 Types.push_back(New);
1632 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001633 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001634}
1635
Mike Stump11289f42009-09-09 15:08:12 +00001636/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001637/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001638QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001639 assert(T->isFunctionType() && "block of function types only");
1640 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001641 // structure.
1642 llvm::FoldingSetNodeID ID;
1643 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001644
Steve Naroffec33ed92008-08-27 16:04:49 +00001645 void *InsertPos = 0;
1646 if (BlockPointerType *PT =
1647 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1648 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001649
1650 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001651 // type either so fill in the canonical type field.
1652 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001653 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001654 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001655
Steve Naroffec33ed92008-08-27 16:04:49 +00001656 // Get the new insert position for the node we care about.
1657 BlockPointerType *NewIP =
1658 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001659 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001660 }
John McCall90d1c2d2009-09-24 23:30:46 +00001661 BlockPointerType *New
1662 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001663 Types.push_back(New);
1664 BlockPointerTypes.InsertNode(New, InsertPos);
1665 return QualType(New, 0);
1666}
1667
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001668/// getLValueReferenceType - Return the uniqued reference to the type for an
1669/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001670QualType
1671ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001672 assert(getCanonicalType(T) != OverloadTy &&
1673 "Unresolved overloaded function type");
1674
Bill Wendling3708c182007-05-27 10:15:43 +00001675 // Unique pointers, to guarantee there is only one pointer of a particular
1676 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001677 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001678 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001679
1680 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001681 if (LValueReferenceType *RT =
1682 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001683 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001684
John McCallfc93cf92009-10-22 22:37:11 +00001685 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1686
Bill Wendling3708c182007-05-27 10:15:43 +00001687 // If the referencee type isn't canonical, this won't be a canonical type
1688 // either, so fill in the canonical type field.
1689 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001690 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1691 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1692 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001693
Bill Wendling3708c182007-05-27 10:15:43 +00001694 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001695 LValueReferenceType *NewIP =
1696 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001697 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001698 }
1699
John McCall90d1c2d2009-09-24 23:30:46 +00001700 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001701 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1702 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001703 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001704 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001705
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001706 return QualType(New, 0);
1707}
1708
1709/// getRValueReferenceType - Return the uniqued reference to the type for an
1710/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001711QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001712 // Unique pointers, to guarantee there is only one pointer of a particular
1713 // structure.
1714 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001715 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001716
1717 void *InsertPos = 0;
1718 if (RValueReferenceType *RT =
1719 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1720 return QualType(RT, 0);
1721
John McCallfc93cf92009-10-22 22:37:11 +00001722 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1723
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001724 // If the referencee type isn't canonical, this won't be a canonical type
1725 // either, so fill in the canonical type field.
1726 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001727 if (InnerRef || !T.isCanonical()) {
1728 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1729 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001730
1731 // Get the new insert position for the node we care about.
1732 RValueReferenceType *NewIP =
1733 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001734 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001735 }
1736
John McCall90d1c2d2009-09-24 23:30:46 +00001737 RValueReferenceType *New
1738 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001739 Types.push_back(New);
1740 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001741 return QualType(New, 0);
1742}
1743
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001744/// getMemberPointerType - Return the uniqued reference to the type for a
1745/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001746QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001747 // Unique pointers, to guarantee there is only one pointer of a particular
1748 // structure.
1749 llvm::FoldingSetNodeID ID;
1750 MemberPointerType::Profile(ID, T, Cls);
1751
1752 void *InsertPos = 0;
1753 if (MemberPointerType *PT =
1754 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1755 return QualType(PT, 0);
1756
1757 // If the pointee or class type isn't canonical, this won't be a canonical
1758 // type either, so fill in the canonical type field.
1759 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001760 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001761 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1762
1763 // Get the new insert position for the node we care about.
1764 MemberPointerType *NewIP =
1765 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001766 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001767 }
John McCall90d1c2d2009-09-24 23:30:46 +00001768 MemberPointerType *New
1769 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001770 Types.push_back(New);
1771 MemberPointerTypes.InsertNode(New, InsertPos);
1772 return QualType(New, 0);
1773}
1774
Mike Stump11289f42009-09-09 15:08:12 +00001775/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001776/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001777QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001778 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001779 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001780 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001781 assert((EltTy->isDependentType() ||
1782 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001783 "Constant array of VLAs is illegal!");
1784
Chris Lattnere2df3f92009-05-13 04:12:56 +00001785 // Convert the array size into a canonical width matching the pointer size for
1786 // the target.
1787 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001788 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001789 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001790
Chris Lattner23b7eb62007-06-15 23:05:46 +00001791 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001792 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001793
Chris Lattner36f8e652007-01-27 08:31:04 +00001794 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001795 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001796 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001797 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001798
John McCall33ddac02011-01-19 10:06:00 +00001799 // If the element type isn't canonical or has qualifiers, this won't
1800 // be a canonical type either, so fill in the canonical type field.
1801 QualType Canon;
1802 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1803 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001804 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001805 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001806 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001807
Chris Lattner36f8e652007-01-27 08:31:04 +00001808 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001809 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001810 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001811 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001812 }
Mike Stump11289f42009-09-09 15:08:12 +00001813
John McCall90d1c2d2009-09-24 23:30:46 +00001814 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001815 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001816 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001817 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001818 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001819}
1820
John McCall06549462011-01-18 08:40:38 +00001821/// getVariableArrayDecayedType - Turns the given type, which may be
1822/// variably-modified, into the corresponding type with all the known
1823/// sizes replaced with [*].
1824QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1825 // Vastly most common case.
1826 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001827
John McCall06549462011-01-18 08:40:38 +00001828 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001829
John McCall06549462011-01-18 08:40:38 +00001830 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001831 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001832 switch (ty->getTypeClass()) {
1833#define TYPE(Class, Base)
1834#define ABSTRACT_TYPE(Class, Base)
1835#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1836#include "clang/AST/TypeNodes.def"
1837 llvm_unreachable("didn't desugar past all non-canonical types?");
1838
1839 // These types should never be variably-modified.
1840 case Type::Builtin:
1841 case Type::Complex:
1842 case Type::Vector:
1843 case Type::ExtVector:
1844 case Type::DependentSizedExtVector:
1845 case Type::ObjCObject:
1846 case Type::ObjCInterface:
1847 case Type::ObjCObjectPointer:
1848 case Type::Record:
1849 case Type::Enum:
1850 case Type::UnresolvedUsing:
1851 case Type::TypeOfExpr:
1852 case Type::TypeOf:
1853 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001854 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001855 case Type::DependentName:
1856 case Type::InjectedClassName:
1857 case Type::TemplateSpecialization:
1858 case Type::DependentTemplateSpecialization:
1859 case Type::TemplateTypeParm:
1860 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001861 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001862 case Type::PackExpansion:
1863 llvm_unreachable("type should never be variably-modified");
1864
1865 // These types can be variably-modified but should never need to
1866 // further decay.
1867 case Type::FunctionNoProto:
1868 case Type::FunctionProto:
1869 case Type::BlockPointer:
1870 case Type::MemberPointer:
1871 return type;
1872
1873 // These types can be variably-modified. All these modifications
1874 // preserve structure except as noted by comments.
1875 // TODO: if we ever care about optimizing VLAs, there are no-op
1876 // optimizations available here.
1877 case Type::Pointer:
1878 result = getPointerType(getVariableArrayDecayedType(
1879 cast<PointerType>(ty)->getPointeeType()));
1880 break;
1881
1882 case Type::LValueReference: {
1883 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1884 result = getLValueReferenceType(
1885 getVariableArrayDecayedType(lv->getPointeeType()),
1886 lv->isSpelledAsLValue());
1887 break;
1888 }
1889
1890 case Type::RValueReference: {
1891 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1892 result = getRValueReferenceType(
1893 getVariableArrayDecayedType(lv->getPointeeType()));
1894 break;
1895 }
1896
Eli Friedman0dfb8892011-10-06 23:00:33 +00001897 case Type::Atomic: {
1898 const AtomicType *at = cast<AtomicType>(ty);
1899 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1900 break;
1901 }
1902
John McCall06549462011-01-18 08:40:38 +00001903 case Type::ConstantArray: {
1904 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1905 result = getConstantArrayType(
1906 getVariableArrayDecayedType(cat->getElementType()),
1907 cat->getSize(),
1908 cat->getSizeModifier(),
1909 cat->getIndexTypeCVRQualifiers());
1910 break;
1911 }
1912
1913 case Type::DependentSizedArray: {
1914 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1915 result = getDependentSizedArrayType(
1916 getVariableArrayDecayedType(dat->getElementType()),
1917 dat->getSizeExpr(),
1918 dat->getSizeModifier(),
1919 dat->getIndexTypeCVRQualifiers(),
1920 dat->getBracketsRange());
1921 break;
1922 }
1923
1924 // Turn incomplete types into [*] types.
1925 case Type::IncompleteArray: {
1926 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1927 result = getVariableArrayType(
1928 getVariableArrayDecayedType(iat->getElementType()),
1929 /*size*/ 0,
1930 ArrayType::Normal,
1931 iat->getIndexTypeCVRQualifiers(),
1932 SourceRange());
1933 break;
1934 }
1935
1936 // Turn VLA types into [*] types.
1937 case Type::VariableArray: {
1938 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1939 result = getVariableArrayType(
1940 getVariableArrayDecayedType(vat->getElementType()),
1941 /*size*/ 0,
1942 ArrayType::Star,
1943 vat->getIndexTypeCVRQualifiers(),
1944 vat->getBracketsRange());
1945 break;
1946 }
1947 }
1948
1949 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001950 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001951}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001952
Steve Naroffcadebd02007-08-30 18:14:25 +00001953/// getVariableArrayType - Returns a non-unique reference to the type for a
1954/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001955QualType ASTContext::getVariableArrayType(QualType EltTy,
1956 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001957 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001958 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001959 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001960 // Since we don't unique expressions, it isn't possible to unique VLA's
1961 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001962 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001963
John McCall33ddac02011-01-19 10:06:00 +00001964 // Be sure to pull qualifiers off the element type.
1965 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1966 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001967 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001968 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00001969 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001970 }
1971
John McCall90d1c2d2009-09-24 23:30:46 +00001972 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001973 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001974
1975 VariableArrayTypes.push_back(New);
1976 Types.push_back(New);
1977 return QualType(New, 0);
1978}
1979
Douglas Gregor4619e432008-12-05 23:32:09 +00001980/// getDependentSizedArrayType - Returns a non-unique reference to
1981/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001982/// type.
John McCall33ddac02011-01-19 10:06:00 +00001983QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1984 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001985 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001986 unsigned elementTypeQuals,
1987 SourceRange brackets) const {
1988 assert((!numElements || numElements->isTypeDependent() ||
1989 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001990 "Size must be type- or value-dependent!");
1991
John McCall33ddac02011-01-19 10:06:00 +00001992 // Dependently-sized array types that do not have a specified number
1993 // of elements will have their sizes deduced from a dependent
1994 // initializer. We do no canonicalization here at all, which is okay
1995 // because they can't be used in most locations.
1996 if (!numElements) {
1997 DependentSizedArrayType *newType
1998 = new (*this, TypeAlignment)
1999 DependentSizedArrayType(*this, elementType, QualType(),
2000 numElements, ASM, elementTypeQuals,
2001 brackets);
2002 Types.push_back(newType);
2003 return QualType(newType, 0);
2004 }
2005
2006 // Otherwise, we actually build a new type every time, but we
2007 // also build a canonical type.
2008
2009 SplitQualType canonElementType = getCanonicalType(elementType).split();
2010
2011 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002012 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002013 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002014 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002015 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002016
John McCall33ddac02011-01-19 10:06:00 +00002017 // Look for an existing type with these properties.
2018 DependentSizedArrayType *canonTy =
2019 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002020
John McCall33ddac02011-01-19 10:06:00 +00002021 // If we don't have one, build one.
2022 if (!canonTy) {
2023 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002024 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002025 QualType(), numElements, ASM, elementTypeQuals,
2026 brackets);
2027 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2028 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002029 }
2030
John McCall33ddac02011-01-19 10:06:00 +00002031 // Apply qualifiers from the element type to the array.
2032 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002033 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002034
John McCall33ddac02011-01-19 10:06:00 +00002035 // If we didn't need extra canonicalization for the element type,
2036 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002037 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002038 return canon;
2039
2040 // Otherwise, we need to build a type which follows the spelling
2041 // of the element type.
2042 DependentSizedArrayType *sugaredType
2043 = new (*this, TypeAlignment)
2044 DependentSizedArrayType(*this, elementType, canon, numElements,
2045 ASM, elementTypeQuals, brackets);
2046 Types.push_back(sugaredType);
2047 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002048}
2049
John McCall33ddac02011-01-19 10:06:00 +00002050QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002051 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002052 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002053 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002054 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002055
John McCall33ddac02011-01-19 10:06:00 +00002056 void *insertPos = 0;
2057 if (IncompleteArrayType *iat =
2058 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2059 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002060
2061 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002062 // either, so fill in the canonical type field. We also have to pull
2063 // qualifiers off the element type.
2064 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002065
John McCall33ddac02011-01-19 10:06:00 +00002066 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2067 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002068 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002069 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002070 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002071
2072 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002073 IncompleteArrayType *existing =
2074 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2075 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002076 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002077
John McCall33ddac02011-01-19 10:06:00 +00002078 IncompleteArrayType *newType = new (*this, TypeAlignment)
2079 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002080
John McCall33ddac02011-01-19 10:06:00 +00002081 IncompleteArrayTypes.InsertNode(newType, insertPos);
2082 Types.push_back(newType);
2083 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002084}
2085
Steve Naroff91fcddb2007-07-18 18:00:27 +00002086/// getVectorType - Return the unique reference to a vector type of
2087/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002088QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002089 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002090 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002091
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002092 // Check if we've already instantiated a vector of this type.
2093 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002094 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002095
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002096 void *InsertPos = 0;
2097 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2098 return QualType(VTP, 0);
2099
2100 // If the element type isn't canonical, this won't be a canonical type either,
2101 // so fill in the canonical type field.
2102 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002103 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002104 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002105
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002106 // Get the new insert position for the node we care about.
2107 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002108 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002109 }
John McCall90d1c2d2009-09-24 23:30:46 +00002110 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002111 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002112 VectorTypes.InsertNode(New, InsertPos);
2113 Types.push_back(New);
2114 return QualType(New, 0);
2115}
2116
Nate Begemance4d7fc2008-04-18 23:10:10 +00002117/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002118/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002119QualType
2120ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002121 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002122
Steve Naroff91fcddb2007-07-18 18:00:27 +00002123 // Check if we've already instantiated a vector of this type.
2124 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002125 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002126 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002127 void *InsertPos = 0;
2128 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2129 return QualType(VTP, 0);
2130
2131 // If the element type isn't canonical, this won't be a canonical type either,
2132 // so fill in the canonical type field.
2133 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002134 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002135 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002136
Steve Naroff91fcddb2007-07-18 18:00:27 +00002137 // Get the new insert position for the node we care about.
2138 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002139 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002140 }
John McCall90d1c2d2009-09-24 23:30:46 +00002141 ExtVectorType *New = new (*this, TypeAlignment)
2142 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002143 VectorTypes.InsertNode(New, InsertPos);
2144 Types.push_back(New);
2145 return QualType(New, 0);
2146}
2147
Jay Foad39c79802011-01-12 09:06:06 +00002148QualType
2149ASTContext::getDependentSizedExtVectorType(QualType vecType,
2150 Expr *SizeExpr,
2151 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002152 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002153 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002154 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002155
Douglas Gregor352169a2009-07-31 03:54:25 +00002156 void *InsertPos = 0;
2157 DependentSizedExtVectorType *Canon
2158 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2159 DependentSizedExtVectorType *New;
2160 if (Canon) {
2161 // We already have a canonical version of this array type; use it as
2162 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002163 New = new (*this, TypeAlignment)
2164 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2165 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002166 } else {
2167 QualType CanonVecTy = getCanonicalType(vecType);
2168 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002169 New = new (*this, TypeAlignment)
2170 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2171 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002172
2173 DependentSizedExtVectorType *CanonCheck
2174 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2175 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2176 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002177 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2178 } else {
2179 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2180 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002181 New = new (*this, TypeAlignment)
2182 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002183 }
2184 }
Mike Stump11289f42009-09-09 15:08:12 +00002185
Douglas Gregor758a8692009-06-17 21:51:59 +00002186 Types.push_back(New);
2187 return QualType(New, 0);
2188}
2189
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002190/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002191///
Jay Foad39c79802011-01-12 09:06:06 +00002192QualType
2193ASTContext::getFunctionNoProtoType(QualType ResultTy,
2194 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002195 const CallingConv DefaultCC = Info.getCC();
2196 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2197 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002198 // Unique functions, to guarantee there is only one function of a particular
2199 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002200 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002201 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002202
Chris Lattner47955de2007-01-27 08:37:20 +00002203 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002204 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002205 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002206 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002207
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002208 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002209 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002210 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002211 Canonical =
2212 getFunctionNoProtoType(getCanonicalType(ResultTy),
2213 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002214
Chris Lattner47955de2007-01-27 08:37:20 +00002215 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002216 FunctionNoProtoType *NewIP =
2217 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002218 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002219 }
Mike Stump11289f42009-09-09 15:08:12 +00002220
Roman Divacky65b88cd2011-03-01 17:40:53 +00002221 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002222 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002223 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002224 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002225 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002226 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002227}
2228
2229/// getFunctionType - Return a normal function type with a typed argument
2230/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002231QualType
2232ASTContext::getFunctionType(QualType ResultTy,
2233 const QualType *ArgArray, unsigned NumArgs,
2234 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002235 // Unique functions, to guarantee there is only one function of a particular
2236 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002237 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002238 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002239
2240 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002241 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002242 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002243 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002244
2245 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002246 bool isCanonical =
2247 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2248 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002249 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002250 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002251 isCanonical = false;
2252
Roman Divacky65b88cd2011-03-01 17:40:53 +00002253 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2254 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2255 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002256
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002257 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002258 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002259 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002260 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002261 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002262 CanonicalArgs.reserve(NumArgs);
2263 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002264 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002265
John McCalldb40c7f2010-12-14 08:05:40 +00002266 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002267 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002268 CanonicalEPI.ExceptionSpecType = EST_None;
2269 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002270 CanonicalEPI.ExtInfo
2271 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2272
Chris Lattner76a00cf2008-04-06 22:59:24 +00002273 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002274 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002275 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002276
Chris Lattnerfd4de792007-01-27 01:15:32 +00002277 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002278 FunctionProtoType *NewIP =
2279 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002280 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002281 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002282
John McCall31168b02011-06-15 23:02:42 +00002283 // FunctionProtoType objects are allocated with extra bytes after
2284 // them for three variable size arrays at the end:
2285 // - parameter types
2286 // - exception types
2287 // - consumed-arguments flags
2288 // Instead of the exception types, there could be a noexcept
2289 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002290 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002291 NumArgs * sizeof(QualType);
2292 if (EPI.ExceptionSpecType == EST_Dynamic)
2293 Size += EPI.NumExceptions * sizeof(QualType);
2294 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002295 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002296 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002297 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002298 }
John McCall31168b02011-06-15 23:02:42 +00002299 if (EPI.ConsumedArguments)
2300 Size += NumArgs * sizeof(bool);
2301
John McCalldb40c7f2010-12-14 08:05:40 +00002302 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002303 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2304 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002305 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002306 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002307 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002308 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002309}
Chris Lattneref51c202006-11-10 07:17:23 +00002310
John McCalle78aac42010-03-10 03:28:59 +00002311#ifndef NDEBUG
2312static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2313 if (!isa<CXXRecordDecl>(D)) return false;
2314 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2315 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2316 return true;
2317 if (RD->getDescribedClassTemplate() &&
2318 !isa<ClassTemplateSpecializationDecl>(RD))
2319 return true;
2320 return false;
2321}
2322#endif
2323
2324/// getInjectedClassNameType - Return the unique reference to the
2325/// injected class name type for the specified templated declaration.
2326QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002327 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002328 assert(NeedsInjectedClassNameType(Decl));
2329 if (Decl->TypeForDecl) {
2330 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002331 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002332 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2333 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2334 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2335 } else {
John McCall424cec92011-01-19 06:33:43 +00002336 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002337 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002338 Decl->TypeForDecl = newType;
2339 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002340 }
2341 return QualType(Decl->TypeForDecl, 0);
2342}
2343
Douglas Gregor83a586e2008-04-13 21:07:44 +00002344/// getTypeDeclType - Return the unique reference to the type for the
2345/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002346QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002347 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002348 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002349
Richard Smithdda56e42011-04-15 14:24:37 +00002350 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002351 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002352
John McCall96f0b5f2010-03-10 06:48:02 +00002353 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2354 "Template type parameter types are always available.");
2355
John McCall81e38502010-02-16 03:57:14 +00002356 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002357 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002358 "struct/union has previous declaration");
2359 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002360 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002361 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002362 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002363 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002364 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002365 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002366 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002367 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2368 Decl->TypeForDecl = newType;
2369 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002370 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002371 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002372
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002373 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002374}
2375
Chris Lattner32d920b2007-01-26 02:01:53 +00002376/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002377/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002378QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002379ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2380 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002381 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002382
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002383 if (Canonical.isNull())
2384 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002385 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002386 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002387 Decl->TypeForDecl = newType;
2388 Types.push_back(newType);
2389 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002390}
2391
Jay Foad39c79802011-01-12 09:06:06 +00002392QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002393 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2394
Douglas Gregorec9fd132012-01-14 16:38:05 +00002395 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002396 if (PrevDecl->TypeForDecl)
2397 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2398
John McCall424cec92011-01-19 06:33:43 +00002399 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2400 Decl->TypeForDecl = newType;
2401 Types.push_back(newType);
2402 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002403}
2404
Jay Foad39c79802011-01-12 09:06:06 +00002405QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002406 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2407
Douglas Gregorec9fd132012-01-14 16:38:05 +00002408 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002409 if (PrevDecl->TypeForDecl)
2410 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2411
John McCall424cec92011-01-19 06:33:43 +00002412 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2413 Decl->TypeForDecl = newType;
2414 Types.push_back(newType);
2415 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002416}
2417
John McCall81904512011-01-06 01:58:22 +00002418QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2419 QualType modifiedType,
2420 QualType equivalentType) {
2421 llvm::FoldingSetNodeID id;
2422 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2423
2424 void *insertPos = 0;
2425 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2426 if (type) return QualType(type, 0);
2427
2428 QualType canon = getCanonicalType(equivalentType);
2429 type = new (*this, TypeAlignment)
2430 AttributedType(canon, attrKind, modifiedType, equivalentType);
2431
2432 Types.push_back(type);
2433 AttributedTypes.InsertNode(type, insertPos);
2434
2435 return QualType(type, 0);
2436}
2437
2438
John McCallcebee162009-10-18 09:09:24 +00002439/// \brief Retrieve a substitution-result type.
2440QualType
2441ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002442 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002443 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002444 && "replacement types must always be canonical");
2445
2446 llvm::FoldingSetNodeID ID;
2447 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2448 void *InsertPos = 0;
2449 SubstTemplateTypeParmType *SubstParm
2450 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2451
2452 if (!SubstParm) {
2453 SubstParm = new (*this, TypeAlignment)
2454 SubstTemplateTypeParmType(Parm, Replacement);
2455 Types.push_back(SubstParm);
2456 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2457 }
2458
2459 return QualType(SubstParm, 0);
2460}
2461
Douglas Gregorada4b792011-01-14 02:55:32 +00002462/// \brief Retrieve a
2463QualType ASTContext::getSubstTemplateTypeParmPackType(
2464 const TemplateTypeParmType *Parm,
2465 const TemplateArgument &ArgPack) {
2466#ifndef NDEBUG
2467 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2468 PEnd = ArgPack.pack_end();
2469 P != PEnd; ++P) {
2470 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2471 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2472 }
2473#endif
2474
2475 llvm::FoldingSetNodeID ID;
2476 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2477 void *InsertPos = 0;
2478 if (SubstTemplateTypeParmPackType *SubstParm
2479 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2480 return QualType(SubstParm, 0);
2481
2482 QualType Canon;
2483 if (!Parm->isCanonicalUnqualified()) {
2484 Canon = getCanonicalType(QualType(Parm, 0));
2485 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2486 ArgPack);
2487 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2488 }
2489
2490 SubstTemplateTypeParmPackType *SubstParm
2491 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2492 ArgPack);
2493 Types.push_back(SubstParm);
2494 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2495 return QualType(SubstParm, 0);
2496}
2497
Douglas Gregoreff93e02009-02-05 23:33:38 +00002498/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002499/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002500/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002501QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002502 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002503 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002504 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002505 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002506 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002507 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002508 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2509
2510 if (TypeParm)
2511 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002512
Chandler Carruth08836322011-05-01 00:51:33 +00002513 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002514 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002515 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002516
2517 TemplateTypeParmType *TypeCheck
2518 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2519 assert(!TypeCheck && "Template type parameter canonical type broken");
2520 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002521 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002522 TypeParm = new (*this, TypeAlignment)
2523 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002524
2525 Types.push_back(TypeParm);
2526 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2527
2528 return QualType(TypeParm, 0);
2529}
2530
John McCalle78aac42010-03-10 03:28:59 +00002531TypeSourceInfo *
2532ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2533 SourceLocation NameLoc,
2534 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002535 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002536 assert(!Name.getAsDependentTemplateName() &&
2537 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002538 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002539
2540 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2541 TemplateSpecializationTypeLoc TL
2542 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002543 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002544 TL.setTemplateNameLoc(NameLoc);
2545 TL.setLAngleLoc(Args.getLAngleLoc());
2546 TL.setRAngleLoc(Args.getRAngleLoc());
2547 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2548 TL.setArgLocInfo(i, Args[i].getLocInfo());
2549 return DI;
2550}
2551
Mike Stump11289f42009-09-09 15:08:12 +00002552QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002553ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002554 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002555 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002556 assert(!Template.getAsDependentTemplateName() &&
2557 "No dependent template names here!");
2558
John McCall6b51f282009-11-23 01:53:49 +00002559 unsigned NumArgs = Args.size();
2560
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002561 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002562 ArgVec.reserve(NumArgs);
2563 for (unsigned i = 0; i != NumArgs; ++i)
2564 ArgVec.push_back(Args[i].getArgument());
2565
John McCall2408e322010-04-27 00:57:59 +00002566 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002567 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002568}
2569
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002570#ifndef NDEBUG
2571static bool hasAnyPackExpansions(const TemplateArgument *Args,
2572 unsigned NumArgs) {
2573 for (unsigned I = 0; I != NumArgs; ++I)
2574 if (Args[I].isPackExpansion())
2575 return true;
2576
2577 return true;
2578}
2579#endif
2580
John McCall0ad16662009-10-29 08:12:44 +00002581QualType
2582ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002583 const TemplateArgument *Args,
2584 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002585 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002586 assert(!Template.getAsDependentTemplateName() &&
2587 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002588 // Look through qualified template names.
2589 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2590 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002591
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002592 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002593 Template.getAsTemplateDecl() &&
2594 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002595 QualType CanonType;
2596 if (!Underlying.isNull())
2597 CanonType = getCanonicalType(Underlying);
2598 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002599 // We can get here with an alias template when the specialization contains
2600 // a pack expansion that does not match up with a parameter pack.
2601 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2602 "Caller must compute aliased type");
2603 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002604 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2605 NumArgs);
2606 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002607
Douglas Gregora8e02e72009-07-28 23:00:59 +00002608 // Allocate the (non-canonical) template specialization type, but don't
2609 // try to unique it: these types typically have location information that
2610 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002611 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2612 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002613 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002614 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002615 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002616 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2617 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002618
Douglas Gregor8bf42052009-02-09 18:46:07 +00002619 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002620 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002621}
2622
Mike Stump11289f42009-09-09 15:08:12 +00002623QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002624ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2625 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002626 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002627 assert(!Template.getAsDependentTemplateName() &&
2628 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002629
Douglas Gregore29139c2011-03-03 17:04:51 +00002630 // Look through qualified template names.
2631 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2632 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002633
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002634 // Build the canonical template specialization type.
2635 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002636 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002637 CanonArgs.reserve(NumArgs);
2638 for (unsigned I = 0; I != NumArgs; ++I)
2639 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2640
2641 // Determine whether this canonical template specialization type already
2642 // exists.
2643 llvm::FoldingSetNodeID ID;
2644 TemplateSpecializationType::Profile(ID, CanonTemplate,
2645 CanonArgs.data(), NumArgs, *this);
2646
2647 void *InsertPos = 0;
2648 TemplateSpecializationType *Spec
2649 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2650
2651 if (!Spec) {
2652 // Allocate a new canonical template specialization type.
2653 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2654 sizeof(TemplateArgument) * NumArgs),
2655 TypeAlignment);
2656 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2657 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002658 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002659 Types.push_back(Spec);
2660 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2661 }
2662
2663 assert(Spec->isDependentType() &&
2664 "Non-dependent template-id type must have a canonical type");
2665 return QualType(Spec, 0);
2666}
2667
2668QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002669ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2670 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002671 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002672 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002673 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002674
2675 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002676 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002677 if (T)
2678 return QualType(T, 0);
2679
Douglas Gregorc42075a2010-02-04 18:10:26 +00002680 QualType Canon = NamedType;
2681 if (!Canon.isCanonical()) {
2682 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002683 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2684 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002685 (void)CheckT;
2686 }
2687
Abramo Bagnara6150c882010-05-11 21:36:43 +00002688 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002689 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002690 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002691 return QualType(T, 0);
2692}
2693
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002694QualType
Jay Foad39c79802011-01-12 09:06:06 +00002695ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002696 llvm::FoldingSetNodeID ID;
2697 ParenType::Profile(ID, InnerType);
2698
2699 void *InsertPos = 0;
2700 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2701 if (T)
2702 return QualType(T, 0);
2703
2704 QualType Canon = InnerType;
2705 if (!Canon.isCanonical()) {
2706 Canon = getCanonicalType(InnerType);
2707 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2708 assert(!CheckT && "Paren canonical type broken");
2709 (void)CheckT;
2710 }
2711
2712 T = new (*this) ParenType(InnerType, Canon);
2713 Types.push_back(T);
2714 ParenTypes.InsertNode(T, InsertPos);
2715 return QualType(T, 0);
2716}
2717
Douglas Gregor02085352010-03-31 20:19:30 +00002718QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2719 NestedNameSpecifier *NNS,
2720 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002721 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002722 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2723
2724 if (Canon.isNull()) {
2725 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002726 ElaboratedTypeKeyword CanonKeyword = Keyword;
2727 if (Keyword == ETK_None)
2728 CanonKeyword = ETK_Typename;
2729
2730 if (CanonNNS != NNS || CanonKeyword != Keyword)
2731 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002732 }
2733
2734 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002735 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002736
2737 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002738 DependentNameType *T
2739 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002740 if (T)
2741 return QualType(T, 0);
2742
Douglas Gregor02085352010-03-31 20:19:30 +00002743 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002744 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002745 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002746 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002747}
2748
Mike Stump11289f42009-09-09 15:08:12 +00002749QualType
John McCallc392f372010-06-11 00:33:02 +00002750ASTContext::getDependentTemplateSpecializationType(
2751 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002752 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002753 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002754 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002755 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002756 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002757 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2758 ArgCopy.push_back(Args[I].getArgument());
2759 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2760 ArgCopy.size(),
2761 ArgCopy.data());
2762}
2763
2764QualType
2765ASTContext::getDependentTemplateSpecializationType(
2766 ElaboratedTypeKeyword Keyword,
2767 NestedNameSpecifier *NNS,
2768 const IdentifierInfo *Name,
2769 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002770 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002771 assert((!NNS || NNS->isDependent()) &&
2772 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002773
Douglas Gregorc42075a2010-02-04 18:10:26 +00002774 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002775 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2776 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002777
2778 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002779 DependentTemplateSpecializationType *T
2780 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002781 if (T)
2782 return QualType(T, 0);
2783
John McCallc392f372010-06-11 00:33:02 +00002784 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002785
John McCallc392f372010-06-11 00:33:02 +00002786 ElaboratedTypeKeyword CanonKeyword = Keyword;
2787 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2788
2789 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002790 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002791 for (unsigned I = 0; I != NumArgs; ++I) {
2792 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2793 if (!CanonArgs[I].structurallyEquals(Args[I]))
2794 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002795 }
2796
John McCallc392f372010-06-11 00:33:02 +00002797 QualType Canon;
2798 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2799 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2800 Name, NumArgs,
2801 CanonArgs.data());
2802
2803 // Find the insert position again.
2804 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2805 }
2806
2807 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2808 sizeof(TemplateArgument) * NumArgs),
2809 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002810 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002811 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002812 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002813 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002814 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002815}
2816
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002817QualType ASTContext::getPackExpansionType(QualType Pattern,
2818 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002819 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002820 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002821
2822 assert(Pattern->containsUnexpandedParameterPack() &&
2823 "Pack expansions must expand one or more parameter packs");
2824 void *InsertPos = 0;
2825 PackExpansionType *T
2826 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2827 if (T)
2828 return QualType(T, 0);
2829
2830 QualType Canon;
2831 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002832 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002833
2834 // Find the insert position again.
2835 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2836 }
2837
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002838 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002839 Types.push_back(T);
2840 PackExpansionTypes.InsertNode(T, InsertPos);
2841 return QualType(T, 0);
2842}
2843
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002844/// CmpProtocolNames - Comparison predicate for sorting protocols
2845/// alphabetically.
2846static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2847 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002848 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002849}
2850
John McCall8b07ec22010-05-15 11:32:37 +00002851static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002852 unsigned NumProtocols) {
2853 if (NumProtocols == 0) return true;
2854
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002855 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2856 return false;
2857
John McCallfc93cf92009-10-22 22:37:11 +00002858 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002859 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2860 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002861 return false;
2862 return true;
2863}
2864
2865static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002866 unsigned &NumProtocols) {
2867 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002868
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002869 // Sort protocols, keyed by name.
2870 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2871
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002872 // Canonicalize.
2873 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2874 Protocols[I] = Protocols[I]->getCanonicalDecl();
2875
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002876 // Remove duplicates.
2877 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2878 NumProtocols = ProtocolsEnd-Protocols;
2879}
2880
John McCall8b07ec22010-05-15 11:32:37 +00002881QualType ASTContext::getObjCObjectType(QualType BaseType,
2882 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002883 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002884 // If the base type is an interface and there aren't any protocols
2885 // to add, then the interface type will do just fine.
2886 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2887 return BaseType;
2888
2889 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002890 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002891 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002892 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002893 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2894 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002895
John McCall8b07ec22010-05-15 11:32:37 +00002896 // Build the canonical type, which has the canonical base type and
2897 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002898 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002899 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2900 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2901 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002902 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002903 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002904 unsigned UniqueCount = NumProtocols;
2905
John McCallfc93cf92009-10-22 22:37:11 +00002906 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002907 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2908 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002909 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002910 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2911 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002912 }
2913
2914 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002915 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2916 }
2917
2918 unsigned Size = sizeof(ObjCObjectTypeImpl);
2919 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2920 void *Mem = Allocate(Size, TypeAlignment);
2921 ObjCObjectTypeImpl *T =
2922 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2923
2924 Types.push_back(T);
2925 ObjCObjectTypes.InsertNode(T, InsertPos);
2926 return QualType(T, 0);
2927}
2928
2929/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2930/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002931QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002932 llvm::FoldingSetNodeID ID;
2933 ObjCObjectPointerType::Profile(ID, ObjectT);
2934
2935 void *InsertPos = 0;
2936 if (ObjCObjectPointerType *QT =
2937 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2938 return QualType(QT, 0);
2939
2940 // Find the canonical object type.
2941 QualType Canonical;
2942 if (!ObjectT.isCanonical()) {
2943 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2944
2945 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002946 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2947 }
2948
Douglas Gregorf85bee62010-02-08 22:59:26 +00002949 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002950 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2951 ObjCObjectPointerType *QType =
2952 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002953
Steve Narofffb4330f2009-06-17 22:40:22 +00002954 Types.push_back(QType);
2955 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002956 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002957}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002958
Douglas Gregor1c283312010-08-11 12:19:30 +00002959/// getObjCInterfaceType - Return the unique reference to the type for the
2960/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002961QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2962 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002963 if (Decl->TypeForDecl)
2964 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002965
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002966 if (PrevDecl) {
2967 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2968 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2969 return QualType(PrevDecl->TypeForDecl, 0);
2970 }
2971
Douglas Gregor7671e532011-12-16 16:34:57 +00002972 // Prefer the definition, if there is one.
2973 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2974 Decl = Def;
2975
Douglas Gregor1c283312010-08-11 12:19:30 +00002976 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2977 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2978 Decl->TypeForDecl = T;
2979 Types.push_back(T);
2980 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002981}
2982
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002983/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2984/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002985/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002986/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002987/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002988QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002989 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002990 if (tofExpr->isTypeDependent()) {
2991 llvm::FoldingSetNodeID ID;
2992 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002993
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002994 void *InsertPos = 0;
2995 DependentTypeOfExprType *Canon
2996 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2997 if (Canon) {
2998 // We already have a "canonical" version of an identical, dependent
2999 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003000 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003001 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003002 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003003 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003004 Canon
3005 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003006 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3007 toe = Canon;
3008 }
3009 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003010 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003011 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003012 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003013 Types.push_back(toe);
3014 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003015}
3016
Steve Naroffa773cd52007-08-01 18:02:17 +00003017/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3018/// TypeOfType AST's. The only motivation to unique these nodes would be
3019/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003020/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003021/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003022QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003023 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003024 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003025 Types.push_back(tot);
3026 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003027}
3028
Anders Carlssonad6bd352009-06-24 21:24:56 +00003029
Anders Carlsson81df7b82009-06-24 19:06:50 +00003030/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3031/// DecltypeType AST's. The only motivation to unique these nodes would be
3032/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003033/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003034/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003035QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003036 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003037
3038 // C++0x [temp.type]p2:
3039 // If an expression e involves a template parameter, decltype(e) denotes a
3040 // unique dependent type. Two such decltype-specifiers refer to the same
3041 // type only if their expressions are equivalent (14.5.6.1).
3042 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003043 llvm::FoldingSetNodeID ID;
3044 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003045
Douglas Gregora21f6c32009-07-30 23:36:40 +00003046 void *InsertPos = 0;
3047 DependentDecltypeType *Canon
3048 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3049 if (Canon) {
3050 // We already have a "canonical" version of an equivalent, dependent
3051 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003052 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003053 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003054 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003055 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003056 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003057 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3058 dt = Canon;
3059 }
3060 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003061 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3062 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003063 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003064 Types.push_back(dt);
3065 return QualType(dt, 0);
3066}
3067
Alexis Hunte852b102011-05-24 22:41:36 +00003068/// getUnaryTransformationType - We don't unique these, since the memory
3069/// savings are minimal and these are rare.
3070QualType ASTContext::getUnaryTransformType(QualType BaseType,
3071 QualType UnderlyingType,
3072 UnaryTransformType::UTTKind Kind)
3073 const {
3074 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003075 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3076 Kind,
3077 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003078 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003079 Types.push_back(Ty);
3080 return QualType(Ty, 0);
3081}
3082
Richard Smithb2bc2e62011-02-21 20:05:19 +00003083/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003084QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003085 void *InsertPos = 0;
3086 if (!DeducedType.isNull()) {
3087 // Look in the folding set for an existing type.
3088 llvm::FoldingSetNodeID ID;
3089 AutoType::Profile(ID, DeducedType);
3090 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3091 return QualType(AT, 0);
3092 }
3093
3094 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3095 Types.push_back(AT);
3096 if (InsertPos)
3097 AutoTypes.InsertNode(AT, InsertPos);
3098 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003099}
3100
Eli Friedman0dfb8892011-10-06 23:00:33 +00003101/// getAtomicType - Return the uniqued reference to the atomic type for
3102/// the given value type.
3103QualType ASTContext::getAtomicType(QualType T) const {
3104 // Unique pointers, to guarantee there is only one pointer of a particular
3105 // structure.
3106 llvm::FoldingSetNodeID ID;
3107 AtomicType::Profile(ID, T);
3108
3109 void *InsertPos = 0;
3110 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3111 return QualType(AT, 0);
3112
3113 // If the atomic value type isn't canonical, this won't be a canonical type
3114 // either, so fill in the canonical type field.
3115 QualType Canonical;
3116 if (!T.isCanonical()) {
3117 Canonical = getAtomicType(getCanonicalType(T));
3118
3119 // Get the new insert position for the node we care about.
3120 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3121 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3122 }
3123 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3124 Types.push_back(New);
3125 AtomicTypes.InsertNode(New, InsertPos);
3126 return QualType(New, 0);
3127}
3128
Richard Smith02e85f32011-04-14 22:09:26 +00003129/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3130QualType ASTContext::getAutoDeductType() const {
3131 if (AutoDeductTy.isNull())
3132 AutoDeductTy = getAutoType(QualType());
3133 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3134 return AutoDeductTy;
3135}
3136
3137/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3138QualType ASTContext::getAutoRRefDeductType() const {
3139 if (AutoRRefDeductTy.isNull())
3140 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3141 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3142 return AutoRRefDeductTy;
3143}
3144
Chris Lattnerfb072462007-01-23 05:45:31 +00003145/// getTagDeclType - Return the unique reference to the type for the
3146/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003147QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003148 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003149 // FIXME: What is the design on getTagDeclType when it requires casting
3150 // away const? mutable?
3151 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003152}
3153
Mike Stump11289f42009-09-09 15:08:12 +00003154/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3155/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3156/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003157CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003158 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003159}
Chris Lattnerfb072462007-01-23 05:45:31 +00003160
Hans Wennborg27541db2011-10-27 08:29:09 +00003161/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3162CanQualType ASTContext::getIntMaxType() const {
3163 return getFromTargetType(Target->getIntMaxType());
3164}
3165
3166/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3167CanQualType ASTContext::getUIntMaxType() const {
3168 return getFromTargetType(Target->getUIntMaxType());
3169}
3170
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003171/// getSignedWCharType - Return the type of "signed wchar_t".
3172/// Used when in C++, as a GCC extension.
3173QualType ASTContext::getSignedWCharType() const {
3174 // FIXME: derive from "Target" ?
3175 return WCharTy;
3176}
3177
3178/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3179/// Used when in C++, as a GCC extension.
3180QualType ASTContext::getUnsignedWCharType() const {
3181 // FIXME: derive from "Target" ?
3182 return UnsignedIntTy;
3183}
3184
Hans Wennborg27541db2011-10-27 08:29:09 +00003185/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003186/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3187QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003188 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003189}
3190
Chris Lattnera21ad802008-04-02 05:18:44 +00003191//===----------------------------------------------------------------------===//
3192// Type Operators
3193//===----------------------------------------------------------------------===//
3194
Jay Foad39c79802011-01-12 09:06:06 +00003195CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003196 // Push qualifiers into arrays, and then discard any remaining
3197 // qualifiers.
3198 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003199 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003200 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003201 QualType Result;
3202 if (isa<ArrayType>(Ty)) {
3203 Result = getArrayDecayedType(QualType(Ty,0));
3204 } else if (isa<FunctionType>(Ty)) {
3205 Result = getPointerType(QualType(Ty, 0));
3206 } else {
3207 Result = QualType(Ty, 0);
3208 }
3209
3210 return CanQualType::CreateUnsafe(Result);
3211}
3212
John McCall6c9dd522011-01-18 07:41:22 +00003213QualType ASTContext::getUnqualifiedArrayType(QualType type,
3214 Qualifiers &quals) {
3215 SplitQualType splitType = type.getSplitUnqualifiedType();
3216
3217 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3218 // the unqualified desugared type and then drops it on the floor.
3219 // We then have to strip that sugar back off with
3220 // getUnqualifiedDesugaredType(), which is silly.
3221 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003222 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003223
3224 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003225 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003226 quals = splitType.Quals;
3227 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003228 }
3229
John McCall6c9dd522011-01-18 07:41:22 +00003230 // Otherwise, recurse on the array's element type.
3231 QualType elementType = AT->getElementType();
3232 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3233
3234 // If that didn't change the element type, AT has no qualifiers, so we
3235 // can just use the results in splitType.
3236 if (elementType == unqualElementType) {
3237 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003238 quals = splitType.Quals;
3239 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003240 }
3241
3242 // Otherwise, add in the qualifiers from the outermost type, then
3243 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003244 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003245
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003246 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003247 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003248 CAT->getSizeModifier(), 0);
3249 }
3250
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003251 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003252 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003253 }
3254
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003255 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003256 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003257 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003258 VAT->getSizeModifier(),
3259 VAT->getIndexTypeCVRQualifiers(),
3260 VAT->getBracketsRange());
3261 }
3262
3263 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003264 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003265 DSAT->getSizeModifier(), 0,
3266 SourceRange());
3267}
3268
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003269/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3270/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3271/// they point to and return true. If T1 and T2 aren't pointer types
3272/// or pointer-to-member types, or if they are not similar at this
3273/// level, returns false and leaves T1 and T2 unchanged. Top-level
3274/// qualifiers on T1 and T2 are ignored. This function will typically
3275/// be called in a loop that successively "unwraps" pointer and
3276/// pointer-to-member types to compare them at each level.
3277bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3278 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3279 *T2PtrType = T2->getAs<PointerType>();
3280 if (T1PtrType && T2PtrType) {
3281 T1 = T1PtrType->getPointeeType();
3282 T2 = T2PtrType->getPointeeType();
3283 return true;
3284 }
3285
3286 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3287 *T2MPType = T2->getAs<MemberPointerType>();
3288 if (T1MPType && T2MPType &&
3289 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3290 QualType(T2MPType->getClass(), 0))) {
3291 T1 = T1MPType->getPointeeType();
3292 T2 = T2MPType->getPointeeType();
3293 return true;
3294 }
3295
David Blaikiebbafb8a2012-03-11 07:00:24 +00003296 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003297 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3298 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3299 if (T1OPType && T2OPType) {
3300 T1 = T1OPType->getPointeeType();
3301 T2 = T2OPType->getPointeeType();
3302 return true;
3303 }
3304 }
3305
3306 // FIXME: Block pointers, too?
3307
3308 return false;
3309}
3310
Jay Foad39c79802011-01-12 09:06:06 +00003311DeclarationNameInfo
3312ASTContext::getNameForTemplate(TemplateName Name,
3313 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003314 switch (Name.getKind()) {
3315 case TemplateName::QualifiedTemplate:
3316 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003317 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003318 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3319 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003320
John McCalld9dfe3a2011-06-30 08:33:18 +00003321 case TemplateName::OverloadedTemplate: {
3322 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3323 // DNInfo work in progress: CHECKME: what about DNLoc?
3324 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3325 }
3326
3327 case TemplateName::DependentTemplate: {
3328 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003329 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003330 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003331 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3332 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003333 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003334 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3335 // DNInfo work in progress: FIXME: source locations?
3336 DeclarationNameLoc DNLoc;
3337 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3338 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3339 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003340 }
3341 }
3342
John McCalld9dfe3a2011-06-30 08:33:18 +00003343 case TemplateName::SubstTemplateTemplateParm: {
3344 SubstTemplateTemplateParmStorage *subst
3345 = Name.getAsSubstTemplateTemplateParm();
3346 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3347 NameLoc);
3348 }
3349
3350 case TemplateName::SubstTemplateTemplateParmPack: {
3351 SubstTemplateTemplateParmPackStorage *subst
3352 = Name.getAsSubstTemplateTemplateParmPack();
3353 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3354 NameLoc);
3355 }
3356 }
3357
3358 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003359}
3360
Jay Foad39c79802011-01-12 09:06:06 +00003361TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003362 switch (Name.getKind()) {
3363 case TemplateName::QualifiedTemplate:
3364 case TemplateName::Template: {
3365 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003366 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003367 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003368 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3369
3370 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003371 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003372 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003373
John McCalld9dfe3a2011-06-30 08:33:18 +00003374 case TemplateName::OverloadedTemplate:
3375 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003376
John McCalld9dfe3a2011-06-30 08:33:18 +00003377 case TemplateName::DependentTemplate: {
3378 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3379 assert(DTN && "Non-dependent template names must refer to template decls.");
3380 return DTN->CanonicalTemplateName;
3381 }
3382
3383 case TemplateName::SubstTemplateTemplateParm: {
3384 SubstTemplateTemplateParmStorage *subst
3385 = Name.getAsSubstTemplateTemplateParm();
3386 return getCanonicalTemplateName(subst->getReplacement());
3387 }
3388
3389 case TemplateName::SubstTemplateTemplateParmPack: {
3390 SubstTemplateTemplateParmPackStorage *subst
3391 = Name.getAsSubstTemplateTemplateParmPack();
3392 TemplateTemplateParmDecl *canonParameter
3393 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3394 TemplateArgument canonArgPack
3395 = getCanonicalTemplateArgument(subst->getArgumentPack());
3396 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3397 }
3398 }
3399
3400 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003401}
3402
Douglas Gregoradee3e32009-11-11 23:06:43 +00003403bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3404 X = getCanonicalTemplateName(X);
3405 Y = getCanonicalTemplateName(Y);
3406 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3407}
3408
Mike Stump11289f42009-09-09 15:08:12 +00003409TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003410ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003411 switch (Arg.getKind()) {
3412 case TemplateArgument::Null:
3413 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003414
Douglas Gregora8e02e72009-07-28 23:00:59 +00003415 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003416 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003417
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003418 case TemplateArgument::Declaration: {
3419 if (Decl *D = Arg.getAsDecl())
3420 return TemplateArgument(D->getCanonicalDecl());
3421 return TemplateArgument((Decl*)0);
3422 }
Mike Stump11289f42009-09-09 15:08:12 +00003423
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003424 case TemplateArgument::Template:
3425 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003426
3427 case TemplateArgument::TemplateExpansion:
3428 return TemplateArgument(getCanonicalTemplateName(
3429 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003430 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003431
Douglas Gregora8e02e72009-07-28 23:00:59 +00003432 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003433 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003434
Douglas Gregora8e02e72009-07-28 23:00:59 +00003435 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003436 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003437
Douglas Gregora8e02e72009-07-28 23:00:59 +00003438 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003439 if (Arg.pack_size() == 0)
3440 return Arg;
3441
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003442 TemplateArgument *CanonArgs
3443 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003444 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003445 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003446 AEnd = Arg.pack_end();
3447 A != AEnd; (void)++A, ++Idx)
3448 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003449
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003450 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003451 }
3452 }
3453
3454 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003455 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003456}
3457
Douglas Gregor333489b2009-03-27 23:10:48 +00003458NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003459ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003460 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003461 return 0;
3462
3463 switch (NNS->getKind()) {
3464 case NestedNameSpecifier::Identifier:
3465 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003466 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003467 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3468 NNS->getAsIdentifier());
3469
3470 case NestedNameSpecifier::Namespace:
3471 // A namespace is canonical; build a nested-name-specifier with
3472 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003473 return NestedNameSpecifier::Create(*this, 0,
3474 NNS->getAsNamespace()->getOriginalNamespace());
3475
3476 case NestedNameSpecifier::NamespaceAlias:
3477 // A namespace is canonical; build a nested-name-specifier with
3478 // this namespace and no prefix.
3479 return NestedNameSpecifier::Create(*this, 0,
3480 NNS->getAsNamespaceAlias()->getNamespace()
3481 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003482
3483 case NestedNameSpecifier::TypeSpec:
3484 case NestedNameSpecifier::TypeSpecWithTemplate: {
3485 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003486
3487 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3488 // break it apart into its prefix and identifier, then reconsititute those
3489 // as the canonical nested-name-specifier. This is required to canonicalize
3490 // a dependent nested-name-specifier involving typedefs of dependent-name
3491 // types, e.g.,
3492 // typedef typename T::type T1;
3493 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003494 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3495 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003496 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003497
Eli Friedman5358a0a2012-03-03 04:09:56 +00003498 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3499 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3500 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003501 return NestedNameSpecifier::Create(*this, 0, false,
3502 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003503 }
3504
3505 case NestedNameSpecifier::Global:
3506 // The global specifier is canonical and unique.
3507 return NNS;
3508 }
3509
David Blaikie8a40f702012-01-17 06:56:22 +00003510 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003511}
3512
Chris Lattner7adf0762008-08-04 07:31:14 +00003513
Jay Foad39c79802011-01-12 09:06:06 +00003514const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003515 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003516 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003517 // Handle the common positive case fast.
3518 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3519 return AT;
3520 }
Mike Stump11289f42009-09-09 15:08:12 +00003521
John McCall8ccfcb52009-09-24 19:53:00 +00003522 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003523 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003524 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003525
John McCall8ccfcb52009-09-24 19:53:00 +00003526 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003527 // implements C99 6.7.3p8: "If the specification of an array type includes
3528 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003529
Chris Lattner7adf0762008-08-04 07:31:14 +00003530 // If we get here, we either have type qualifiers on the type, or we have
3531 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003532 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003533
John McCall33ddac02011-01-19 10:06:00 +00003534 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003535 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003536
Chris Lattner7adf0762008-08-04 07:31:14 +00003537 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003538 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003539 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003540 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003541
Chris Lattner7adf0762008-08-04 07:31:14 +00003542 // Otherwise, we have an array and we have qualifiers on it. Push the
3543 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003544 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003545
Chris Lattner7adf0762008-08-04 07:31:14 +00003546 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3547 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3548 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003549 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003550 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3551 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3552 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003553 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003554
Mike Stump11289f42009-09-09 15:08:12 +00003555 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003556 = dyn_cast<DependentSizedArrayType>(ATy))
3557 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003558 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003559 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003560 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003561 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003562 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003563
Chris Lattner7adf0762008-08-04 07:31:14 +00003564 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003565 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003566 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003567 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003568 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003569 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003570}
3571
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003572QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003573 // C99 6.7.5.3p7:
3574 // A declaration of a parameter as "array of type" shall be
3575 // adjusted to "qualified pointer to type", where the type
3576 // qualifiers (if any) are those specified within the [ and ] of
3577 // the array type derivation.
3578 if (T->isArrayType())
3579 return getArrayDecayedType(T);
3580
3581 // C99 6.7.5.3p8:
3582 // A declaration of a parameter as "function returning type"
3583 // shall be adjusted to "pointer to function returning type", as
3584 // in 6.3.2.1.
3585 if (T->isFunctionType())
3586 return getPointerType(T);
3587
3588 return T;
3589}
3590
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003591QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003592 T = getVariableArrayDecayedType(T);
3593 T = getAdjustedParameterType(T);
3594 return T.getUnqualifiedType();
3595}
3596
Chris Lattnera21ad802008-04-02 05:18:44 +00003597/// getArrayDecayedType - Return the properly qualified result of decaying the
3598/// specified array type to a pointer. This operation is non-trivial when
3599/// handling typedefs etc. The canonical type of "T" must be an array type,
3600/// this returns a pointer to a properly qualified element of the array.
3601///
3602/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003603QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003604 // Get the element type with 'getAsArrayType' so that we don't lose any
3605 // typedefs in the element type of the array. This also handles propagation
3606 // of type qualifiers from the array type into the element type if present
3607 // (C99 6.7.3p8).
3608 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3609 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003610
Chris Lattner7adf0762008-08-04 07:31:14 +00003611 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003612
3613 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003614 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003615}
3616
John McCall33ddac02011-01-19 10:06:00 +00003617QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3618 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003619}
3620
John McCall33ddac02011-01-19 10:06:00 +00003621QualType ASTContext::getBaseElementType(QualType type) const {
3622 Qualifiers qs;
3623 while (true) {
3624 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003625 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003626 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003627
John McCall33ddac02011-01-19 10:06:00 +00003628 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003629 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003630 }
Mike Stump11289f42009-09-09 15:08:12 +00003631
John McCall33ddac02011-01-19 10:06:00 +00003632 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003633}
3634
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003635/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003636uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003637ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3638 uint64_t ElementCount = 1;
3639 do {
3640 ElementCount *= CA->getSize().getZExtValue();
3641 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3642 } while (CA);
3643 return ElementCount;
3644}
3645
Steve Naroff0af91202007-04-27 21:51:21 +00003646/// getFloatingRank - Return a relative rank for floating point types.
3647/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003648static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003649 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003650 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003651
John McCall9dd450b2009-09-21 23:43:11 +00003652 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3653 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003654 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003655 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003656 case BuiltinType::Float: return FloatRank;
3657 case BuiltinType::Double: return DoubleRank;
3658 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003659 }
3660}
3661
Mike Stump11289f42009-09-09 15:08:12 +00003662/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3663/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003664/// 'typeDomain' is a real floating point or complex type.
3665/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003666QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3667 QualType Domain) const {
3668 FloatingRank EltRank = getFloatingRank(Size);
3669 if (Domain->isComplexType()) {
3670 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003671 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003672 case FloatRank: return FloatComplexTy;
3673 case DoubleRank: return DoubleComplexTy;
3674 case LongDoubleRank: return LongDoubleComplexTy;
3675 }
Steve Naroff0af91202007-04-27 21:51:21 +00003676 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003677
3678 assert(Domain->isRealFloatingType() && "Unknown domain!");
3679 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003680 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003681 case FloatRank: return FloatTy;
3682 case DoubleRank: return DoubleTy;
3683 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003684 }
David Blaikief47fa302012-01-17 02:30:50 +00003685 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003686}
3687
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003688/// getFloatingTypeOrder - Compare the rank of the two specified floating
3689/// point types, ignoring the domain of the type (i.e. 'double' ==
3690/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003691/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003692int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003693 FloatingRank LHSR = getFloatingRank(LHS);
3694 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003695
Chris Lattnerb90739d2008-04-06 23:38:49 +00003696 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003697 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003698 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003699 return 1;
3700 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003701}
3702
Chris Lattner76a00cf2008-04-06 22:59:24 +00003703/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3704/// routine will assert if passed a built-in type that isn't an integer or enum,
3705/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003706unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003707 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003708
Chris Lattner76a00cf2008-04-06 22:59:24 +00003709 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003710 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003711 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003712 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003713 case BuiltinType::Char_S:
3714 case BuiltinType::Char_U:
3715 case BuiltinType::SChar:
3716 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003717 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003718 case BuiltinType::Short:
3719 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003720 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003721 case BuiltinType::Int:
3722 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003723 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003724 case BuiltinType::Long:
3725 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003726 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003727 case BuiltinType::LongLong:
3728 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003729 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003730 case BuiltinType::Int128:
3731 case BuiltinType::UInt128:
3732 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003733 }
3734}
3735
Eli Friedman629ffb92009-08-20 04:21:42 +00003736/// \brief Whether this is a promotable bitfield reference according
3737/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3738///
3739/// \returns the type this bit-field will promote to, or NULL if no
3740/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003741QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003742 if (E->isTypeDependent() || E->isValueDependent())
3743 return QualType();
3744
Eli Friedman629ffb92009-08-20 04:21:42 +00003745 FieldDecl *Field = E->getBitField();
3746 if (!Field)
3747 return QualType();
3748
3749 QualType FT = Field->getType();
3750
Richard Smithcaf33902011-10-10 18:28:20 +00003751 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003752 uint64_t IntSize = getTypeSize(IntTy);
3753 // GCC extension compatibility: if the bit-field size is less than or equal
3754 // to the size of int, it gets promoted no matter what its type is.
3755 // For instance, unsigned long bf : 4 gets promoted to signed int.
3756 if (BitWidth < IntSize)
3757 return IntTy;
3758
3759 if (BitWidth == IntSize)
3760 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3761
3762 // Types bigger than int are not subject to promotions, and therefore act
3763 // like the base type.
3764 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3765 // is ridiculous.
3766 return QualType();
3767}
3768
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003769/// getPromotedIntegerType - Returns the type that Promotable will
3770/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3771/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003772QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003773 assert(!Promotable.isNull());
3774 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003775 if (const EnumType *ET = Promotable->getAs<EnumType>())
3776 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003777
3778 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3779 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3780 // (3.9.1) can be converted to a prvalue of the first of the following
3781 // types that can represent all the values of its underlying type:
3782 // int, unsigned int, long int, unsigned long int, long long int, or
3783 // unsigned long long int [...]
3784 // FIXME: Is there some better way to compute this?
3785 if (BT->getKind() == BuiltinType::WChar_S ||
3786 BT->getKind() == BuiltinType::WChar_U ||
3787 BT->getKind() == BuiltinType::Char16 ||
3788 BT->getKind() == BuiltinType::Char32) {
3789 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3790 uint64_t FromSize = getTypeSize(BT);
3791 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3792 LongLongTy, UnsignedLongLongTy };
3793 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3794 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3795 if (FromSize < ToSize ||
3796 (FromSize == ToSize &&
3797 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3798 return PromoteTypes[Idx];
3799 }
3800 llvm_unreachable("char type should fit into long long");
3801 }
3802 }
3803
3804 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003805 if (Promotable->isSignedIntegerType())
3806 return IntTy;
3807 uint64_t PromotableSize = getTypeSize(Promotable);
3808 uint64_t IntSize = getTypeSize(IntTy);
3809 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3810 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3811}
3812
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003813/// \brief Recurses in pointer/array types until it finds an objc retainable
3814/// type and returns its ownership.
3815Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3816 while (!T.isNull()) {
3817 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3818 return T.getObjCLifetime();
3819 if (T->isArrayType())
3820 T = getBaseElementType(T);
3821 else if (const PointerType *PT = T->getAs<PointerType>())
3822 T = PT->getPointeeType();
3823 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003824 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003825 else
3826 break;
3827 }
3828
3829 return Qualifiers::OCL_None;
3830}
3831
Mike Stump11289f42009-09-09 15:08:12 +00003832/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003833/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003834/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003835int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003836 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3837 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003838 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003839
Chris Lattner76a00cf2008-04-06 22:59:24 +00003840 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3841 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003842
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003843 unsigned LHSRank = getIntegerRank(LHSC);
3844 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003845
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003846 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3847 if (LHSRank == RHSRank) return 0;
3848 return LHSRank > RHSRank ? 1 : -1;
3849 }
Mike Stump11289f42009-09-09 15:08:12 +00003850
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003851 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3852 if (LHSUnsigned) {
3853 // If the unsigned [LHS] type is larger, return it.
3854 if (LHSRank >= RHSRank)
3855 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003856
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003857 // If the signed type can represent all values of the unsigned type, it
3858 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003859 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003860 return -1;
3861 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003862
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003863 // If the unsigned [RHS] type is larger, return it.
3864 if (RHSRank >= LHSRank)
3865 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003866
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003867 // If the signed type can represent all values of the unsigned type, it
3868 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003869 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003870 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003871}
Anders Carlsson98f07902007-08-17 05:31:46 +00003872
Anders Carlsson6d417272009-11-14 21:45:58 +00003873static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003874CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3875 DeclContext *DC, IdentifierInfo *Id) {
3876 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003877 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003878 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003879 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003880 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003881}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003882
Mike Stump11289f42009-09-09 15:08:12 +00003883// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003884QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003885 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003886 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003887 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003888 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003889 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003890
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003891 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003892
Anders Carlsson98f07902007-08-17 05:31:46 +00003893 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003894 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003895 // int flags;
3896 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003897 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003898 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003899 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003900 FieldTypes[3] = LongTy;
3901
Anders Carlsson98f07902007-08-17 05:31:46 +00003902 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003903 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003904 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003905 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003906 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003907 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003908 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003909 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003910 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003911 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003912 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003913 }
3914
Douglas Gregord5058122010-02-11 01:19:42 +00003915 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003916 }
Mike Stump11289f42009-09-09 15:08:12 +00003917
Anders Carlsson98f07902007-08-17 05:31:46 +00003918 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003919}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003920
Douglas Gregor512b0772009-04-23 22:29:11 +00003921void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003922 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003923 assert(Rec && "Invalid CFConstantStringType");
3924 CFConstantStringTypeDecl = Rec->getDecl();
3925}
3926
Jay Foad39c79802011-01-12 09:06:06 +00003927QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003928 if (BlockDescriptorType)
3929 return getTagDeclType(BlockDescriptorType);
3930
3931 RecordDecl *T;
3932 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003933 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003934 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003935 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003936
3937 QualType FieldTypes[] = {
3938 UnsignedLongTy,
3939 UnsignedLongTy,
3940 };
3941
3942 const char *FieldNames[] = {
3943 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003944 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003945 };
3946
3947 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003948 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003949 SourceLocation(),
3950 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003951 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003952 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003953 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003954 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003955 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003956 T->addDecl(Field);
3957 }
3958
Douglas Gregord5058122010-02-11 01:19:42 +00003959 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003960
3961 BlockDescriptorType = T;
3962
3963 return getTagDeclType(BlockDescriptorType);
3964}
3965
Jay Foad39c79802011-01-12 09:06:06 +00003966QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003967 if (BlockDescriptorExtendedType)
3968 return getTagDeclType(BlockDescriptorExtendedType);
3969
3970 RecordDecl *T;
3971 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003972 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003973 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003974 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003975
3976 QualType FieldTypes[] = {
3977 UnsignedLongTy,
3978 UnsignedLongTy,
3979 getPointerType(VoidPtrTy),
3980 getPointerType(VoidPtrTy)
3981 };
3982
3983 const char *FieldNames[] = {
3984 "reserved",
3985 "Size",
3986 "CopyFuncPtr",
3987 "DestroyFuncPtr"
3988 };
3989
3990 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003991 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003992 SourceLocation(),
3993 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003994 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003995 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003996 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003997 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00003998 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003999 T->addDecl(Field);
4000 }
4001
Douglas Gregord5058122010-02-11 01:19:42 +00004002 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004003
4004 BlockDescriptorExtendedType = T;
4005
4006 return getTagDeclType(BlockDescriptorExtendedType);
4007}
4008
Jay Foad39c79802011-01-12 09:06:06 +00004009bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004010 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004011 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004012 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004013 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4014 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004015 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004016
4017 }
4018 }
Mike Stump94967902009-10-21 18:16:27 +00004019 return false;
4020}
4021
Jay Foad39c79802011-01-12 09:06:06 +00004022QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004023ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004024 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004025 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004026 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004027 // unsigned int __flags;
4028 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004029 // void *__copy_helper; // as needed
4030 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004031 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004032 // } *
4033
Mike Stump94967902009-10-21 18:16:27 +00004034 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4035
4036 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004037 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004038 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4039 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004040 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004041 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004042 T->startDefinition();
4043 QualType Int32Ty = IntTy;
4044 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4045 QualType FieldTypes[] = {
4046 getPointerType(VoidPtrTy),
4047 getPointerType(getTagDeclType(T)),
4048 Int32Ty,
4049 Int32Ty,
4050 getPointerType(VoidPtrTy),
4051 getPointerType(VoidPtrTy),
4052 Ty
4053 };
4054
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004055 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004056 "__isa",
4057 "__forwarding",
4058 "__flags",
4059 "__size",
4060 "__copy_helper",
4061 "__destroy_helper",
4062 DeclName,
4063 };
4064
4065 for (size_t i = 0; i < 7; ++i) {
4066 if (!HasCopyAndDispose && i >=4 && i <= 5)
4067 continue;
4068 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004069 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004070 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004071 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004072 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004073 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004074 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004075 T->addDecl(Field);
4076 }
4077
Douglas Gregord5058122010-02-11 01:19:42 +00004078 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004079
4080 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004081}
4082
Douglas Gregorbab8a962011-09-08 01:46:34 +00004083TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4084 if (!ObjCInstanceTypeDecl)
4085 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4086 getTranslationUnitDecl(),
4087 SourceLocation(),
4088 SourceLocation(),
4089 &Idents.get("instancetype"),
4090 getTrivialTypeSourceInfo(getObjCIdType()));
4091 return ObjCInstanceTypeDecl;
4092}
4093
Anders Carlsson18acd442007-10-29 06:33:42 +00004094// This returns true if a type has been typedefed to BOOL:
4095// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004096static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004097 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004098 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4099 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004100
Anders Carlssond8499822007-10-29 05:01:08 +00004101 return false;
4102}
4103
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004104/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004105/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004106CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004107 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4108 return CharUnits::Zero();
4109
Ken Dyck40775002010-01-11 17:06:35 +00004110 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004111
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004112 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004113 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004114 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004115 // Treat arrays as pointers, since that's how they're passed in.
4116 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004117 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004118 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004119}
4120
4121static inline
4122std::string charUnitsToString(const CharUnits &CU) {
4123 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004124}
4125
John McCall351762c2011-02-07 10:33:21 +00004126/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004127/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004128std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4129 std::string S;
4130
David Chisnall950a9512009-11-17 19:33:30 +00004131 const BlockDecl *Decl = Expr->getBlockDecl();
4132 QualType BlockTy =
4133 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4134 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004135 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004136 // Compute size of all parameters.
4137 // Start with computing size of a pointer in number of bytes.
4138 // FIXME: There might(should) be a better way of doing this computation!
4139 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004140 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4141 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004142 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004143 E = Decl->param_end(); PI != E; ++PI) {
4144 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004145 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004146 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004147 ParmOffset += sz;
4148 }
4149 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004150 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004151 // Block pointer and offset.
4152 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004153
4154 // Argument types.
4155 ParmOffset = PtrSize;
4156 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4157 Decl->param_end(); PI != E; ++PI) {
4158 ParmVarDecl *PVDecl = *PI;
4159 QualType PType = PVDecl->getOriginalType();
4160 if (const ArrayType *AT =
4161 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4162 // Use array's original type only if it has known number of
4163 // elements.
4164 if (!isa<ConstantArrayType>(AT))
4165 PType = PVDecl->getType();
4166 } else if (PType->isFunctionType())
4167 PType = PVDecl->getType();
4168 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004169 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004170 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004171 }
John McCall351762c2011-02-07 10:33:21 +00004172
4173 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004174}
4175
Douglas Gregora9d84932011-05-27 01:19:52 +00004176bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004177 std::string& S) {
4178 // Encode result type.
4179 getObjCEncodingForType(Decl->getResultType(), S);
4180 CharUnits ParmOffset;
4181 // Compute size of all parameters.
4182 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4183 E = Decl->param_end(); PI != E; ++PI) {
4184 QualType PType = (*PI)->getType();
4185 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004186 if (sz.isZero())
4187 return true;
4188
David Chisnall50e4eba2010-12-30 14:05:53 +00004189 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004190 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004191 ParmOffset += sz;
4192 }
4193 S += charUnitsToString(ParmOffset);
4194 ParmOffset = CharUnits::Zero();
4195
4196 // Argument types.
4197 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4198 E = Decl->param_end(); PI != E; ++PI) {
4199 ParmVarDecl *PVDecl = *PI;
4200 QualType PType = PVDecl->getOriginalType();
4201 if (const ArrayType *AT =
4202 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4203 // Use array's original type only if it has known number of
4204 // elements.
4205 if (!isa<ConstantArrayType>(AT))
4206 PType = PVDecl->getType();
4207 } else if (PType->isFunctionType())
4208 PType = PVDecl->getType();
4209 getObjCEncodingForType(PType, S);
4210 S += charUnitsToString(ParmOffset);
4211 ParmOffset += getObjCEncodingTypeSize(PType);
4212 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004213
4214 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004215}
4216
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004217/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4218/// method parameter or return type. If Extended, include class names and
4219/// block object types.
4220void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4221 QualType T, std::string& S,
4222 bool Extended) const {
4223 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4224 getObjCEncodingForTypeQualifier(QT, S);
4225 // Encode parameter type.
4226 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4227 true /*OutermostType*/,
4228 false /*EncodingProperty*/,
4229 false /*StructField*/,
4230 Extended /*EncodeBlockParameters*/,
4231 Extended /*EncodeClassNames*/);
4232}
4233
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004234/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004235/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004236bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004237 std::string& S,
4238 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004239 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004240 // Encode return type.
4241 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4242 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004243 // Compute size of all parameters.
4244 // Start with computing size of a pointer in number of bytes.
4245 // FIXME: There might(should) be a better way of doing this computation!
4246 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004247 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004248 // The first two arguments (self and _cmd) are pointers; account for
4249 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004250 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004251 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004252 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004253 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004254 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004255 if (sz.isZero())
4256 return true;
4257
Ken Dyck40775002010-01-11 17:06:35 +00004258 assert (sz.isPositive() &&
4259 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004260 ParmOffset += sz;
4261 }
Ken Dyck40775002010-01-11 17:06:35 +00004262 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004263 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004264 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004265
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004266 // Argument types.
4267 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004268 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004269 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004270 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004271 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004272 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004273 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4274 // Use array's original type only if it has known number of
4275 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004276 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004277 PType = PVDecl->getType();
4278 } else if (PType->isFunctionType())
4279 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004280 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4281 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004282 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004283 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004284 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004285
4286 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004287}
4288
Daniel Dunbar4932b362008-08-28 04:38:10 +00004289/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004290/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004291/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4292/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004293/// Property attributes are stored as a comma-delimited C string. The simple
4294/// attributes readonly and bycopy are encoded as single characters. The
4295/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4296/// encoded as single characters, followed by an identifier. Property types
4297/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004298/// these attributes are defined by the following enumeration:
4299/// @code
4300/// enum PropertyAttributes {
4301/// kPropertyReadOnly = 'R', // property is read-only.
4302/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4303/// kPropertyByref = '&', // property is a reference to the value last assigned
4304/// kPropertyDynamic = 'D', // property is dynamic
4305/// kPropertyGetter = 'G', // followed by getter selector name
4306/// kPropertySetter = 'S', // followed by setter selector name
4307/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004308/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004309/// kPropertyWeak = 'W' // 'weak' property
4310/// kPropertyStrong = 'P' // property GC'able
4311/// kPropertyNonAtomic = 'N' // property non-atomic
4312/// };
4313/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004314void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004315 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004316 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004317 // Collect information from the property implementation decl(s).
4318 bool Dynamic = false;
4319 ObjCPropertyImplDecl *SynthesizePID = 0;
4320
4321 // FIXME: Duplicated code due to poor abstraction.
4322 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004323 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004324 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4325 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004326 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004327 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004328 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004329 if (PID->getPropertyDecl() == PD) {
4330 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4331 Dynamic = true;
4332 } else {
4333 SynthesizePID = PID;
4334 }
4335 }
4336 }
4337 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004338 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004339 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004340 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004341 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004342 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004343 if (PID->getPropertyDecl() == PD) {
4344 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4345 Dynamic = true;
4346 } else {
4347 SynthesizePID = PID;
4348 }
4349 }
Mike Stump11289f42009-09-09 15:08:12 +00004350 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004351 }
4352 }
4353
4354 // FIXME: This is not very efficient.
4355 S = "T";
4356
4357 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004358 // GCC has some special rules regarding encoding of properties which
4359 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004360 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004361 true /* outermost type */,
4362 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004363
4364 if (PD->isReadOnly()) {
4365 S += ",R";
4366 } else {
4367 switch (PD->getSetterKind()) {
4368 case ObjCPropertyDecl::Assign: break;
4369 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004370 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004371 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004372 }
4373 }
4374
4375 // It really isn't clear at all what this means, since properties
4376 // are "dynamic by default".
4377 if (Dynamic)
4378 S += ",D";
4379
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004380 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4381 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004382
Daniel Dunbar4932b362008-08-28 04:38:10 +00004383 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4384 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004385 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004386 }
4387
4388 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4389 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004390 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004391 }
4392
4393 if (SynthesizePID) {
4394 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4395 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004396 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004397 }
4398
4399 // FIXME: OBJCGC: weak & strong
4400}
4401
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004402/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004403/// Another legacy compatibility encoding: 32-bit longs are encoded as
4404/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004405/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4406///
4407void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004408 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004409 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004410 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004411 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004412 else
Jay Foad39c79802011-01-12 09:06:06 +00004413 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004414 PointeeTy = IntTy;
4415 }
4416 }
4417}
4418
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004419void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004420 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004421 // We follow the behavior of gcc, expanding structures which are
4422 // directly pointed to, and expanding embedded structures. Note that
4423 // these rules are sufficient to prevent recursive encoding of the
4424 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004425 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004426 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004427}
4428
David Chisnallb190a2c2010-06-04 01:10:52 +00004429static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4430 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004431 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004432 case BuiltinType::Void: return 'v';
4433 case BuiltinType::Bool: return 'B';
4434 case BuiltinType::Char_U:
4435 case BuiltinType::UChar: return 'C';
4436 case BuiltinType::UShort: return 'S';
4437 case BuiltinType::UInt: return 'I';
4438 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004439 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004440 case BuiltinType::UInt128: return 'T';
4441 case BuiltinType::ULongLong: return 'Q';
4442 case BuiltinType::Char_S:
4443 case BuiltinType::SChar: return 'c';
4444 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004445 case BuiltinType::WChar_S:
4446 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004447 case BuiltinType::Int: return 'i';
4448 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004449 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004450 case BuiltinType::LongLong: return 'q';
4451 case BuiltinType::Int128: return 't';
4452 case BuiltinType::Float: return 'f';
4453 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004454 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004455 }
4456}
4457
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004458static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4459 EnumDecl *Enum = ET->getDecl();
4460
4461 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4462 if (!Enum->isFixed())
4463 return 'i';
4464
4465 // The encoding of a fixed enum type matches its fixed underlying type.
4466 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4467}
4468
Jay Foad39c79802011-01-12 09:06:06 +00004469static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004470 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004471 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004472 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004473 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4474 // The GNU runtime requires more information; bitfields are encoded as b,
4475 // then the offset (in bits) of the first element, then the type of the
4476 // bitfield, then the size in bits. For example, in this structure:
4477 //
4478 // struct
4479 // {
4480 // int integer;
4481 // int flags:2;
4482 // };
4483 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4484 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4485 // information is not especially sensible, but we're stuck with it for
4486 // compatibility with GCC, although providing it breaks anything that
4487 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004488 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004489 const RecordDecl *RD = FD->getParent();
4490 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004491 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004492 if (const EnumType *ET = T->getAs<EnumType>())
4493 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004494 else
Jay Foad39c79802011-01-12 09:06:06 +00004495 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004496 }
Richard Smithcaf33902011-10-10 18:28:20 +00004497 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004498}
4499
Daniel Dunbar07d07852009-10-18 21:17:35 +00004500// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004501void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4502 bool ExpandPointedToStructures,
4503 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004504 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004505 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004506 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004507 bool StructField,
4508 bool EncodeBlockParameters,
4509 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004510 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004511 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004512 return EncodeBitField(this, S, T, FD);
4513 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004514 return;
4515 }
Mike Stump11289f42009-09-09 15:08:12 +00004516
John McCall9dd450b2009-09-21 23:43:11 +00004517 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004518 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004519 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004520 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004521 return;
4522 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004523
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004524 // encoding for pointer or r3eference types.
4525 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004526 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004527 if (PT->isObjCSelType()) {
4528 S += ':';
4529 return;
4530 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004531 PointeeTy = PT->getPointeeType();
4532 }
4533 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4534 PointeeTy = RT->getPointeeType();
4535 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004536 bool isReadOnly = false;
4537 // For historical/compatibility reasons, the read-only qualifier of the
4538 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4539 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004540 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004541 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004542 if (OutermostType && T.isConstQualified()) {
4543 isReadOnly = true;
4544 S += 'r';
4545 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004546 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004547 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004548 while (P->getAs<PointerType>())
4549 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004550 if (P.isConstQualified()) {
4551 isReadOnly = true;
4552 S += 'r';
4553 }
4554 }
4555 if (isReadOnly) {
4556 // Another legacy compatibility encoding. Some ObjC qualifier and type
4557 // combinations need to be rearranged.
4558 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004559 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004560 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004561 }
Mike Stump11289f42009-09-09 15:08:12 +00004562
Anders Carlssond8499822007-10-29 05:01:08 +00004563 if (PointeeTy->isCharType()) {
4564 // char pointer types should be encoded as '*' unless it is a
4565 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004566 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004567 S += '*';
4568 return;
4569 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004570 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004571 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4572 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4573 S += '#';
4574 return;
4575 }
4576 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4577 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4578 S += '@';
4579 return;
4580 }
4581 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004582 }
Anders Carlssond8499822007-10-29 05:01:08 +00004583 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004584 getLegacyIntegralTypeEncoding(PointeeTy);
4585
Mike Stump11289f42009-09-09 15:08:12 +00004586 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004587 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004588 return;
4589 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004590
Chris Lattnere7cabb92009-07-13 00:10:46 +00004591 if (const ArrayType *AT =
4592 // Ignore type qualifiers etc.
4593 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004594 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004595 // Incomplete arrays are encoded as a pointer to the array element.
4596 S += '^';
4597
Mike Stump11289f42009-09-09 15:08:12 +00004598 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004599 false, ExpandStructures, FD);
4600 } else {
4601 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004602
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004603 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4604 if (getTypeSize(CAT->getElementType()) == 0)
4605 S += '0';
4606 else
4607 S += llvm::utostr(CAT->getSize().getZExtValue());
4608 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004609 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004610 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4611 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004612 S += '0';
4613 }
Mike Stump11289f42009-09-09 15:08:12 +00004614
4615 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004616 false, ExpandStructures, FD);
4617 S += ']';
4618 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004619 return;
4620 }
Mike Stump11289f42009-09-09 15:08:12 +00004621
John McCall9dd450b2009-09-21 23:43:11 +00004622 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004623 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004624 return;
4625 }
Mike Stump11289f42009-09-09 15:08:12 +00004626
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004627 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004628 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004629 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004630 // Anonymous structures print as '?'
4631 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4632 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004633 if (ClassTemplateSpecializationDecl *Spec
4634 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4635 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4636 std::string TemplateArgsStr
4637 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004638 TemplateArgs.data(),
4639 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004640 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004641
4642 S += TemplateArgsStr;
4643 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004644 } else {
4645 S += '?';
4646 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004647 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004648 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004649 if (!RDecl->isUnion()) {
4650 getObjCEncodingForStructureImpl(RDecl, S, FD);
4651 } else {
4652 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4653 FieldEnd = RDecl->field_end();
4654 Field != FieldEnd; ++Field) {
4655 if (FD) {
4656 S += '"';
4657 S += Field->getNameAsString();
4658 S += '"';
4659 }
Mike Stump11289f42009-09-09 15:08:12 +00004660
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004661 // Special case bit-fields.
4662 if (Field->isBitField()) {
4663 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004664 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004665 } else {
4666 QualType qt = Field->getType();
4667 getLegacyIntegralTypeEncoding(qt);
4668 getObjCEncodingForTypeImpl(qt, S, false, true,
4669 FD, /*OutermostType*/false,
4670 /*EncodingProperty*/false,
4671 /*StructField*/true);
4672 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004673 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004674 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004675 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004676 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004677 return;
4678 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004679
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004680 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004681 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004682 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004683 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004684 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004685 return;
4686 }
Mike Stump11289f42009-09-09 15:08:12 +00004687
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004688 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004689 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004690 if (EncodeBlockParameters) {
4691 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4692
4693 S += '<';
4694 // Block return type
4695 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4696 ExpandPointedToStructures, ExpandStructures,
4697 FD,
4698 false /* OutermostType */,
4699 EncodingProperty,
4700 false /* StructField */,
4701 EncodeBlockParameters,
4702 EncodeClassNames);
4703 // Block self
4704 S += "@?";
4705 // Block parameters
4706 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4707 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4708 E = FPT->arg_type_end(); I && (I != E); ++I) {
4709 getObjCEncodingForTypeImpl(*I, S,
4710 ExpandPointedToStructures,
4711 ExpandStructures,
4712 FD,
4713 false /* OutermostType */,
4714 EncodingProperty,
4715 false /* StructField */,
4716 EncodeBlockParameters,
4717 EncodeClassNames);
4718 }
4719 }
4720 S += '>';
4721 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004722 return;
4723 }
Mike Stump11289f42009-09-09 15:08:12 +00004724
John McCall8b07ec22010-05-15 11:32:37 +00004725 // Ignore protocol qualifiers when mangling at this level.
4726 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4727 T = OT->getBaseType();
4728
John McCall8ccfcb52009-09-24 19:53:00 +00004729 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004730 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004731 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004732 S += '{';
4733 const IdentifierInfo *II = OI->getIdentifier();
4734 S += II->getName();
4735 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004736 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004737 DeepCollectObjCIvars(OI, true, Ivars);
4738 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004739 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004740 if (Field->isBitField())
4741 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004742 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004743 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004744 }
4745 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004746 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004747 }
Mike Stump11289f42009-09-09 15:08:12 +00004748
John McCall9dd450b2009-09-21 23:43:11 +00004749 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004750 if (OPT->isObjCIdType()) {
4751 S += '@';
4752 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004753 }
Mike Stump11289f42009-09-09 15:08:12 +00004754
Steve Narofff0c86112009-10-28 22:03:49 +00004755 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4756 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4757 // Since this is a binary compatibility issue, need to consult with runtime
4758 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004759 S += '#';
4760 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004761 }
Mike Stump11289f42009-09-09 15:08:12 +00004762
Chris Lattnere7cabb92009-07-13 00:10:46 +00004763 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004764 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004765 ExpandPointedToStructures,
4766 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004767 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004768 // Note that we do extended encoding of protocol qualifer list
4769 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004770 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004771 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4772 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004773 S += '<';
4774 S += (*I)->getNameAsString();
4775 S += '>';
4776 }
4777 S += '"';
4778 }
4779 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004780 }
Mike Stump11289f42009-09-09 15:08:12 +00004781
Chris Lattnere7cabb92009-07-13 00:10:46 +00004782 QualType PointeeTy = OPT->getPointeeType();
4783 if (!EncodingProperty &&
4784 isa<TypedefType>(PointeeTy.getTypePtr())) {
4785 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004786 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004787 // {...};
4788 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004789 getObjCEncodingForTypeImpl(PointeeTy, S,
4790 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004791 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004792 return;
4793 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004794
4795 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004796 if (OPT->getInterfaceDecl() &&
4797 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004798 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004799 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004800 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4801 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004802 S += '<';
4803 S += (*I)->getNameAsString();
4804 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004805 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004806 S += '"';
4807 }
4808 return;
4809 }
Mike Stump11289f42009-09-09 15:08:12 +00004810
John McCalla9e6e8d2010-05-17 23:56:34 +00004811 // gcc just blithely ignores member pointers.
4812 // TODO: maybe there should be a mangling for these
4813 if (T->getAs<MemberPointerType>())
4814 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004815
4816 if (T->isVectorType()) {
4817 // This matches gcc's encoding, even though technically it is
4818 // insufficient.
4819 // FIXME. We should do a better job than gcc.
4820 return;
4821 }
4822
David Blaikie83d382b2011-09-23 05:06:16 +00004823 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004824}
4825
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004826void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4827 std::string &S,
4828 const FieldDecl *FD,
4829 bool includeVBases) const {
4830 assert(RDecl && "Expected non-null RecordDecl");
4831 assert(!RDecl->isUnion() && "Should not be called for unions");
4832 if (!RDecl->getDefinition())
4833 return;
4834
4835 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4836 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4837 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4838
4839 if (CXXRec) {
4840 for (CXXRecordDecl::base_class_iterator
4841 BI = CXXRec->bases_begin(),
4842 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4843 if (!BI->isVirtual()) {
4844 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004845 if (base->isEmpty())
4846 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004847 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4848 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4849 std::make_pair(offs, base));
4850 }
4851 }
4852 }
4853
4854 unsigned i = 0;
4855 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4856 FieldEnd = RDecl->field_end();
4857 Field != FieldEnd; ++Field, ++i) {
4858 uint64_t offs = layout.getFieldOffset(i);
4859 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004860 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004861 }
4862
4863 if (CXXRec && includeVBases) {
4864 for (CXXRecordDecl::base_class_iterator
4865 BI = CXXRec->vbases_begin(),
4866 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4867 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004868 if (base->isEmpty())
4869 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004870 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004871 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4872 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4873 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004874 }
4875 }
4876
4877 CharUnits size;
4878 if (CXXRec) {
4879 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4880 } else {
4881 size = layout.getSize();
4882 }
4883
4884 uint64_t CurOffs = 0;
4885 std::multimap<uint64_t, NamedDecl *>::iterator
4886 CurLayObj = FieldOrBaseOffsets.begin();
4887
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004888 if (CXXRec && CXXRec->isDynamicClass() &&
4889 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004890 if (FD) {
4891 S += "\"_vptr$";
4892 std::string recname = CXXRec->getNameAsString();
4893 if (recname.empty()) recname = "?";
4894 S += recname;
4895 S += '"';
4896 }
4897 S += "^^?";
4898 CurOffs += getTypeSize(VoidPtrTy);
4899 }
4900
4901 if (!RDecl->hasFlexibleArrayMember()) {
4902 // Mark the end of the structure.
4903 uint64_t offs = toBits(size);
4904 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4905 std::make_pair(offs, (NamedDecl*)0));
4906 }
4907
4908 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4909 assert(CurOffs <= CurLayObj->first);
4910
4911 if (CurOffs < CurLayObj->first) {
4912 uint64_t padding = CurLayObj->first - CurOffs;
4913 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4914 // packing/alignment of members is different that normal, in which case
4915 // the encoding will be out-of-sync with the real layout.
4916 // If the runtime switches to just consider the size of types without
4917 // taking into account alignment, we could make padding explicit in the
4918 // encoding (e.g. using arrays of chars). The encoding strings would be
4919 // longer then though.
4920 CurOffs += padding;
4921 }
4922
4923 NamedDecl *dcl = CurLayObj->second;
4924 if (dcl == 0)
4925 break; // reached end of structure.
4926
4927 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4928 // We expand the bases without their virtual bases since those are going
4929 // in the initial structure. Note that this differs from gcc which
4930 // expands virtual bases each time one is encountered in the hierarchy,
4931 // making the encoding type bigger than it really is.
4932 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004933 assert(!base->isEmpty());
4934 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004935 } else {
4936 FieldDecl *field = cast<FieldDecl>(dcl);
4937 if (FD) {
4938 S += '"';
4939 S += field->getNameAsString();
4940 S += '"';
4941 }
4942
4943 if (field->isBitField()) {
4944 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004945 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004946 } else {
4947 QualType qt = field->getType();
4948 getLegacyIntegralTypeEncoding(qt);
4949 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4950 /*OutermostType*/false,
4951 /*EncodingProperty*/false,
4952 /*StructField*/true);
4953 CurOffs += getTypeSize(field->getType());
4954 }
4955 }
4956 }
4957}
4958
Mike Stump11289f42009-09-09 15:08:12 +00004959void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004960 std::string& S) const {
4961 if (QT & Decl::OBJC_TQ_In)
4962 S += 'n';
4963 if (QT & Decl::OBJC_TQ_Inout)
4964 S += 'N';
4965 if (QT & Decl::OBJC_TQ_Out)
4966 S += 'o';
4967 if (QT & Decl::OBJC_TQ_Bycopy)
4968 S += 'O';
4969 if (QT & Decl::OBJC_TQ_Byref)
4970 S += 'R';
4971 if (QT & Decl::OBJC_TQ_Oneway)
4972 S += 'V';
4973}
4974
Douglas Gregor3ea72692011-08-12 05:46:01 +00004975TypedefDecl *ASTContext::getObjCIdDecl() const {
4976 if (!ObjCIdDecl) {
4977 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4978 T = getObjCObjectPointerType(T);
4979 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4980 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4981 getTranslationUnitDecl(),
4982 SourceLocation(), SourceLocation(),
4983 &Idents.get("id"), IdInfo);
4984 }
4985
4986 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004987}
4988
Douglas Gregor52e02802011-08-12 06:17:30 +00004989TypedefDecl *ASTContext::getObjCSelDecl() const {
4990 if (!ObjCSelDecl) {
4991 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4992 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4993 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4994 getTranslationUnitDecl(),
4995 SourceLocation(), SourceLocation(),
4996 &Idents.get("SEL"), SelInfo);
4997 }
4998 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004999}
5000
Douglas Gregor0a586182011-08-12 05:59:41 +00005001TypedefDecl *ASTContext::getObjCClassDecl() const {
5002 if (!ObjCClassDecl) {
5003 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5004 T = getObjCObjectPointerType(T);
5005 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5006 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5007 getTranslationUnitDecl(),
5008 SourceLocation(), SourceLocation(),
5009 &Idents.get("Class"), ClassInfo);
5010 }
5011
5012 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005013}
5014
Douglas Gregord53ae832012-01-17 18:09:05 +00005015ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5016 if (!ObjCProtocolClassDecl) {
5017 ObjCProtocolClassDecl
5018 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5019 SourceLocation(),
5020 &Idents.get("Protocol"),
5021 /*PrevDecl=*/0,
5022 SourceLocation(), true);
5023 }
5024
5025 return ObjCProtocolClassDecl;
5026}
5027
Meador Inge5d3fb222012-06-16 03:34:49 +00005028//===----------------------------------------------------------------------===//
5029// __builtin_va_list Construction Functions
5030//===----------------------------------------------------------------------===//
5031
5032static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5033 // typedef char* __builtin_va_list;
5034 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5035 TypeSourceInfo *TInfo
5036 = Context->getTrivialTypeSourceInfo(CharPtrType);
5037
5038 TypedefDecl *VaListTypeDecl
5039 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5040 Context->getTranslationUnitDecl(),
5041 SourceLocation(), SourceLocation(),
5042 &Context->Idents.get("__builtin_va_list"),
5043 TInfo);
5044 return VaListTypeDecl;
5045}
5046
5047static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5048 // typedef void* __builtin_va_list;
5049 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5050 TypeSourceInfo *TInfo
5051 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5052
5053 TypedefDecl *VaListTypeDecl
5054 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5055 Context->getTranslationUnitDecl(),
5056 SourceLocation(), SourceLocation(),
5057 &Context->Idents.get("__builtin_va_list"),
5058 TInfo);
5059 return VaListTypeDecl;
5060}
5061
5062static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5063 // typedef struct __va_list_tag {
5064 RecordDecl *VaListTagDecl;
5065
5066 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5067 Context->getTranslationUnitDecl(),
5068 &Context->Idents.get("__va_list_tag"));
5069 VaListTagDecl->startDefinition();
5070
5071 const size_t NumFields = 5;
5072 QualType FieldTypes[NumFields];
5073 const char *FieldNames[NumFields];
5074
5075 // unsigned char gpr;
5076 FieldTypes[0] = Context->UnsignedCharTy;
5077 FieldNames[0] = "gpr";
5078
5079 // unsigned char fpr;
5080 FieldTypes[1] = Context->UnsignedCharTy;
5081 FieldNames[1] = "fpr";
5082
5083 // unsigned short reserved;
5084 FieldTypes[2] = Context->UnsignedShortTy;
5085 FieldNames[2] = "reserved";
5086
5087 // void* overflow_arg_area;
5088 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5089 FieldNames[3] = "overflow_arg_area";
5090
5091 // void* reg_save_area;
5092 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5093 FieldNames[4] = "reg_save_area";
5094
5095 // Create fields
5096 for (unsigned i = 0; i < NumFields; ++i) {
5097 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5098 SourceLocation(),
5099 SourceLocation(),
5100 &Context->Idents.get(FieldNames[i]),
5101 FieldTypes[i], /*TInfo=*/0,
5102 /*BitWidth=*/0,
5103 /*Mutable=*/false,
5104 ICIS_NoInit);
5105 Field->setAccess(AS_public);
5106 VaListTagDecl->addDecl(Field);
5107 }
5108 VaListTagDecl->completeDefinition();
5109 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5110
5111 // } __va_list_tag;
5112 TypedefDecl *VaListTagTypedefDecl
5113 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5114 Context->getTranslationUnitDecl(),
5115 SourceLocation(), SourceLocation(),
5116 &Context->Idents.get("__va_list_tag"),
5117 Context->getTrivialTypeSourceInfo(VaListTagType));
5118 QualType VaListTagTypedefType =
5119 Context->getTypedefType(VaListTagTypedefDecl);
5120
5121 // typedef __va_list_tag __builtin_va_list[1];
5122 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5123 QualType VaListTagArrayType
5124 = Context->getConstantArrayType(VaListTagTypedefType,
5125 Size, ArrayType::Normal, 0);
5126 TypeSourceInfo *TInfo
5127 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5128 TypedefDecl *VaListTypedefDecl
5129 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5130 Context->getTranslationUnitDecl(),
5131 SourceLocation(), SourceLocation(),
5132 &Context->Idents.get("__builtin_va_list"),
5133 TInfo);
5134
5135 return VaListTypedefDecl;
5136}
5137
5138static TypedefDecl *
5139CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5140 // typedef struct __va_list_tag {
5141 RecordDecl *VaListTagDecl;
5142 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5143 Context->getTranslationUnitDecl(),
5144 &Context->Idents.get("__va_list_tag"));
5145 VaListTagDecl->startDefinition();
5146
5147 const size_t NumFields = 4;
5148 QualType FieldTypes[NumFields];
5149 const char *FieldNames[NumFields];
5150
5151 // unsigned gp_offset;
5152 FieldTypes[0] = Context->UnsignedIntTy;
5153 FieldNames[0] = "gp_offset";
5154
5155 // unsigned fp_offset;
5156 FieldTypes[1] = Context->UnsignedIntTy;
5157 FieldNames[1] = "fp_offset";
5158
5159 // void* overflow_arg_area;
5160 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5161 FieldNames[2] = "overflow_arg_area";
5162
5163 // void* reg_save_area;
5164 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5165 FieldNames[3] = "reg_save_area";
5166
5167 // Create fields
5168 for (unsigned i = 0; i < NumFields; ++i) {
5169 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5170 VaListTagDecl,
5171 SourceLocation(),
5172 SourceLocation(),
5173 &Context->Idents.get(FieldNames[i]),
5174 FieldTypes[i], /*TInfo=*/0,
5175 /*BitWidth=*/0,
5176 /*Mutable=*/false,
5177 ICIS_NoInit);
5178 Field->setAccess(AS_public);
5179 VaListTagDecl->addDecl(Field);
5180 }
5181 VaListTagDecl->completeDefinition();
5182 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5183
5184 // } __va_list_tag;
5185 TypedefDecl *VaListTagTypedefDecl
5186 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5187 Context->getTranslationUnitDecl(),
5188 SourceLocation(), SourceLocation(),
5189 &Context->Idents.get("__va_list_tag"),
5190 Context->getTrivialTypeSourceInfo(VaListTagType));
5191 QualType VaListTagTypedefType =
5192 Context->getTypedefType(VaListTagTypedefDecl);
5193
5194 // typedef __va_list_tag __builtin_va_list[1];
5195 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5196 QualType VaListTagArrayType
5197 = Context->getConstantArrayType(VaListTagTypedefType,
5198 Size, ArrayType::Normal,0);
5199 TypeSourceInfo *TInfo
5200 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5201 TypedefDecl *VaListTypedefDecl
5202 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5203 Context->getTranslationUnitDecl(),
5204 SourceLocation(), SourceLocation(),
5205 &Context->Idents.get("__builtin_va_list"),
5206 TInfo);
5207
5208 return VaListTypedefDecl;
5209}
5210
5211static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5212 // typedef int __builtin_va_list[4];
5213 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5214 QualType IntArrayType
5215 = Context->getConstantArrayType(Context->IntTy,
5216 Size, ArrayType::Normal, 0);
5217 TypedefDecl *VaListTypedefDecl
5218 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5219 Context->getTranslationUnitDecl(),
5220 SourceLocation(), SourceLocation(),
5221 &Context->Idents.get("__builtin_va_list"),
5222 Context->getTrivialTypeSourceInfo(IntArrayType));
5223
5224 return VaListTypedefDecl;
5225}
5226
5227static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5228 TargetInfo::BuiltinVaListKind Kind) {
5229 switch (Kind) {
5230 case TargetInfo::CharPtrBuiltinVaList:
5231 return CreateCharPtrBuiltinVaListDecl(Context);
5232 case TargetInfo::VoidPtrBuiltinVaList:
5233 return CreateVoidPtrBuiltinVaListDecl(Context);
5234 case TargetInfo::PowerABIBuiltinVaList:
5235 return CreatePowerABIBuiltinVaListDecl(Context);
5236 case TargetInfo::X86_64ABIBuiltinVaList:
5237 return CreateX86_64ABIBuiltinVaListDecl(Context);
5238 case TargetInfo::PNaClABIBuiltinVaList:
5239 return CreatePNaClABIBuiltinVaListDecl(Context);
5240 }
5241
5242 llvm_unreachable("Unhandled __builtin_va_list type kind");
5243}
5244
5245TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5246 if (!BuiltinVaListDecl)
5247 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5248
5249 return BuiltinVaListDecl;
5250}
5251
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005252void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005253 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005254 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005255
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005256 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005257}
5258
John McCalld28ae272009-12-02 08:04:21 +00005259/// \brief Retrieve the template name that corresponds to a non-empty
5260/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005261TemplateName
5262ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5263 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005264 unsigned size = End - Begin;
5265 assert(size > 1 && "set is not overloaded!");
5266
5267 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5268 size * sizeof(FunctionTemplateDecl*));
5269 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5270
5271 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005272 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005273 NamedDecl *D = *I;
5274 assert(isa<FunctionTemplateDecl>(D) ||
5275 (isa<UsingShadowDecl>(D) &&
5276 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5277 *Storage++ = D;
5278 }
5279
5280 return TemplateName(OT);
5281}
5282
Douglas Gregordc572a32009-03-30 22:58:21 +00005283/// \brief Retrieve the template name that represents a qualified
5284/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005285TemplateName
5286ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5287 bool TemplateKeyword,
5288 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005289 assert(NNS && "Missing nested-name-specifier in qualified template name");
5290
Douglas Gregorc42075a2010-02-04 18:10:26 +00005291 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005292 llvm::FoldingSetNodeID ID;
5293 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5294
5295 void *InsertPos = 0;
5296 QualifiedTemplateName *QTN =
5297 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5298 if (!QTN) {
5299 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5300 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5301 }
5302
5303 return TemplateName(QTN);
5304}
5305
5306/// \brief Retrieve the template name that represents a dependent
5307/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005308TemplateName
5309ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5310 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005311 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005312 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005313
5314 llvm::FoldingSetNodeID ID;
5315 DependentTemplateName::Profile(ID, NNS, Name);
5316
5317 void *InsertPos = 0;
5318 DependentTemplateName *QTN =
5319 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5320
5321 if (QTN)
5322 return TemplateName(QTN);
5323
5324 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5325 if (CanonNNS == NNS) {
5326 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5327 } else {
5328 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5329 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005330 DependentTemplateName *CheckQTN =
5331 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5332 assert(!CheckQTN && "Dependent type name canonicalization broken");
5333 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005334 }
5335
5336 DependentTemplateNames.InsertNode(QTN, InsertPos);
5337 return TemplateName(QTN);
5338}
5339
Douglas Gregor71395fa2009-11-04 00:56:37 +00005340/// \brief Retrieve the template name that represents a dependent
5341/// template name such as \c MetaFun::template operator+.
5342TemplateName
5343ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005344 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005345 assert((!NNS || NNS->isDependent()) &&
5346 "Nested name specifier must be dependent");
5347
5348 llvm::FoldingSetNodeID ID;
5349 DependentTemplateName::Profile(ID, NNS, Operator);
5350
5351 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005352 DependentTemplateName *QTN
5353 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005354
5355 if (QTN)
5356 return TemplateName(QTN);
5357
5358 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5359 if (CanonNNS == NNS) {
5360 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5361 } else {
5362 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5363 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005364
5365 DependentTemplateName *CheckQTN
5366 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5367 assert(!CheckQTN && "Dependent template name canonicalization broken");
5368 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005369 }
5370
5371 DependentTemplateNames.InsertNode(QTN, InsertPos);
5372 return TemplateName(QTN);
5373}
5374
Douglas Gregor5590be02011-01-15 06:45:20 +00005375TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005376ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5377 TemplateName replacement) const {
5378 llvm::FoldingSetNodeID ID;
5379 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5380
5381 void *insertPos = 0;
5382 SubstTemplateTemplateParmStorage *subst
5383 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5384
5385 if (!subst) {
5386 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5387 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5388 }
5389
5390 return TemplateName(subst);
5391}
5392
5393TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005394ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5395 const TemplateArgument &ArgPack) const {
5396 ASTContext &Self = const_cast<ASTContext &>(*this);
5397 llvm::FoldingSetNodeID ID;
5398 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5399
5400 void *InsertPos = 0;
5401 SubstTemplateTemplateParmPackStorage *Subst
5402 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5403
5404 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005405 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005406 ArgPack.pack_size(),
5407 ArgPack.pack_begin());
5408 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5409 }
5410
5411 return TemplateName(Subst);
5412}
5413
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005414/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005415/// TargetInfo, produce the corresponding type. The unsigned @p Type
5416/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005417CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005418 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005419 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005420 case TargetInfo::SignedShort: return ShortTy;
5421 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5422 case TargetInfo::SignedInt: return IntTy;
5423 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5424 case TargetInfo::SignedLong: return LongTy;
5425 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5426 case TargetInfo::SignedLongLong: return LongLongTy;
5427 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5428 }
5429
David Blaikie83d382b2011-09-23 05:06:16 +00005430 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005431}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005432
5433//===----------------------------------------------------------------------===//
5434// Type Predicates.
5435//===----------------------------------------------------------------------===//
5436
Fariborz Jahanian96207692009-02-18 21:49:28 +00005437/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5438/// garbage collection attribute.
5439///
John McCall553d45a2011-01-12 00:34:59 +00005440Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005441 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005442 return Qualifiers::GCNone;
5443
David Blaikiebbafb8a2012-03-11 07:00:24 +00005444 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005445 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5446
5447 // Default behaviour under objective-C's gc is for ObjC pointers
5448 // (or pointers to them) be treated as though they were declared
5449 // as __strong.
5450 if (GCAttrs == Qualifiers::GCNone) {
5451 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5452 return Qualifiers::Strong;
5453 else if (Ty->isPointerType())
5454 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5455 } else {
5456 // It's not valid to set GC attributes on anything that isn't a
5457 // pointer.
5458#ifndef NDEBUG
5459 QualType CT = Ty->getCanonicalTypeInternal();
5460 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5461 CT = AT->getElementType();
5462 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5463#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005464 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005465 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005466}
5467
Chris Lattner49af6a42008-04-07 06:51:04 +00005468//===----------------------------------------------------------------------===//
5469// Type Compatibility Testing
5470//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005471
Mike Stump11289f42009-09-09 15:08:12 +00005472/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005473/// compatible.
5474static bool areCompatVectorTypes(const VectorType *LHS,
5475 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005476 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005477 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005478 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005479}
5480
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005481bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5482 QualType SecondVec) {
5483 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5484 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5485
5486 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5487 return true;
5488
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005489 // Treat Neon vector types and most AltiVec vector types as if they are the
5490 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005491 const VectorType *First = FirstVec->getAs<VectorType>();
5492 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005493 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005494 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005495 First->getVectorKind() != VectorType::AltiVecPixel &&
5496 First->getVectorKind() != VectorType::AltiVecBool &&
5497 Second->getVectorKind() != VectorType::AltiVecPixel &&
5498 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005499 return true;
5500
5501 return false;
5502}
5503
Steve Naroff8e6aee52009-07-23 01:01:38 +00005504//===----------------------------------------------------------------------===//
5505// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5506//===----------------------------------------------------------------------===//
5507
5508/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5509/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005510bool
5511ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5512 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005513 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005514 return true;
5515 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5516 E = rProto->protocol_end(); PI != E; ++PI)
5517 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5518 return true;
5519 return false;
5520}
5521
Steve Naroff8e6aee52009-07-23 01:01:38 +00005522/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5523/// return true if lhs's protocols conform to rhs's protocol; false
5524/// otherwise.
5525bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5526 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5527 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5528 return false;
5529}
5530
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005531/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5532/// Class<p1, ...>.
5533bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5534 QualType rhs) {
5535 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5536 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5537 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5538
5539 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5540 E = lhsQID->qual_end(); I != E; ++I) {
5541 bool match = false;
5542 ObjCProtocolDecl *lhsProto = *I;
5543 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5544 E = rhsOPT->qual_end(); J != E; ++J) {
5545 ObjCProtocolDecl *rhsProto = *J;
5546 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5547 match = true;
5548 break;
5549 }
5550 }
5551 if (!match)
5552 return false;
5553 }
5554 return true;
5555}
5556
Steve Naroff8e6aee52009-07-23 01:01:38 +00005557/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5558/// ObjCQualifiedIDType.
5559bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5560 bool compare) {
5561 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005562 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005563 lhs->isObjCIdType() || lhs->isObjCClassType())
5564 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005565 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005566 rhs->isObjCIdType() || rhs->isObjCClassType())
5567 return true;
5568
5569 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005570 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005571
Steve Naroff8e6aee52009-07-23 01:01:38 +00005572 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005573
Steve Naroff8e6aee52009-07-23 01:01:38 +00005574 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005575 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005576 // make sure we check the class hierarchy.
5577 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5578 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5579 E = lhsQID->qual_end(); I != E; ++I) {
5580 // when comparing an id<P> on lhs with a static type on rhs,
5581 // see if static class implements all of id's protocols, directly or
5582 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005583 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005584 return false;
5585 }
5586 }
5587 // If there are no qualifiers and no interface, we have an 'id'.
5588 return true;
5589 }
Mike Stump11289f42009-09-09 15:08:12 +00005590 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005591 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5592 E = lhsQID->qual_end(); I != E; ++I) {
5593 ObjCProtocolDecl *lhsProto = *I;
5594 bool match = false;
5595
5596 // when comparing an id<P> on lhs with a static type on rhs,
5597 // see if static class implements all of id's protocols, directly or
5598 // through its super class and categories.
5599 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5600 E = rhsOPT->qual_end(); J != E; ++J) {
5601 ObjCProtocolDecl *rhsProto = *J;
5602 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5603 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5604 match = true;
5605 break;
5606 }
5607 }
Mike Stump11289f42009-09-09 15:08:12 +00005608 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005609 // make sure we check the class hierarchy.
5610 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5611 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5612 E = lhsQID->qual_end(); I != E; ++I) {
5613 // when comparing an id<P> on lhs with a static type on rhs,
5614 // see if static class implements all of id's protocols, directly or
5615 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005616 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005617 match = true;
5618 break;
5619 }
5620 }
5621 }
5622 if (!match)
5623 return false;
5624 }
Mike Stump11289f42009-09-09 15:08:12 +00005625
Steve Naroff8e6aee52009-07-23 01:01:38 +00005626 return true;
5627 }
Mike Stump11289f42009-09-09 15:08:12 +00005628
Steve Naroff8e6aee52009-07-23 01:01:38 +00005629 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5630 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5631
Mike Stump11289f42009-09-09 15:08:12 +00005632 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005633 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005634 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005635 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5636 E = lhsOPT->qual_end(); I != E; ++I) {
5637 ObjCProtocolDecl *lhsProto = *I;
5638 bool match = false;
5639
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005640 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005641 // see if static class implements all of id's protocols, directly or
5642 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005643 // First, lhs protocols in the qualifier list must be found, direct
5644 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005645 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5646 E = rhsQID->qual_end(); J != E; ++J) {
5647 ObjCProtocolDecl *rhsProto = *J;
5648 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5649 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5650 match = true;
5651 break;
5652 }
5653 }
5654 if (!match)
5655 return false;
5656 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005657
5658 // Static class's protocols, or its super class or category protocols
5659 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5660 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5661 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5662 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5663 // This is rather dubious but matches gcc's behavior. If lhs has
5664 // no type qualifier and its class has no static protocol(s)
5665 // assume that it is mismatch.
5666 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5667 return false;
5668 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5669 LHSInheritedProtocols.begin(),
5670 E = LHSInheritedProtocols.end(); I != E; ++I) {
5671 bool match = false;
5672 ObjCProtocolDecl *lhsProto = (*I);
5673 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5674 E = rhsQID->qual_end(); J != E; ++J) {
5675 ObjCProtocolDecl *rhsProto = *J;
5676 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5677 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5678 match = true;
5679 break;
5680 }
5681 }
5682 if (!match)
5683 return false;
5684 }
5685 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005686 return true;
5687 }
5688 return false;
5689}
5690
Eli Friedman47f77112008-08-22 00:56:42 +00005691/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005692/// compatible for assignment from RHS to LHS. This handles validation of any
5693/// protocol qualifiers on the LHS or RHS.
5694///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005695bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5696 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005697 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5698 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5699
Steve Naroff1329fa02009-07-15 18:40:39 +00005700 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005701 if (LHS->isObjCUnqualifiedIdOrClass() ||
5702 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005703 return true;
5704
John McCall8b07ec22010-05-15 11:32:37 +00005705 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005706 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5707 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005708 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005709
5710 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5711 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5712 QualType(RHSOPT,0));
5713
John McCall8b07ec22010-05-15 11:32:37 +00005714 // If we have 2 user-defined types, fall into that path.
5715 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005716 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005717
Steve Naroff8e6aee52009-07-23 01:01:38 +00005718 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005719}
5720
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005721/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005722/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005723/// arguments in block literals. When passed as arguments, passing 'A*' where
5724/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5725/// not OK. For the return type, the opposite is not OK.
5726bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5727 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005728 const ObjCObjectPointerType *RHSOPT,
5729 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005730 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005731 return true;
5732
5733 if (LHSOPT->isObjCBuiltinType()) {
5734 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5735 }
5736
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005737 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005738 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5739 QualType(RHSOPT,0),
5740 false);
5741
5742 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5743 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5744 if (LHS && RHS) { // We have 2 user-defined types.
5745 if (LHS != RHS) {
5746 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005747 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005748 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005749 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005750 }
5751 else
5752 return true;
5753 }
5754 return false;
5755}
5756
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005757/// getIntersectionOfProtocols - This routine finds the intersection of set
5758/// of protocols inherited from two distinct objective-c pointer objects.
5759/// It is used to build composite qualifier list of the composite type of
5760/// the conditional expression involving two objective-c pointer objects.
5761static
5762void getIntersectionOfProtocols(ASTContext &Context,
5763 const ObjCObjectPointerType *LHSOPT,
5764 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005765 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005766
John McCall8b07ec22010-05-15 11:32:37 +00005767 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5768 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5769 assert(LHS->getInterface() && "LHS must have an interface base");
5770 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005771
5772 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5773 unsigned LHSNumProtocols = LHS->getNumProtocols();
5774 if (LHSNumProtocols > 0)
5775 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5776 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005777 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005778 Context.CollectInheritedProtocols(LHS->getInterface(),
5779 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005780 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5781 LHSInheritedProtocols.end());
5782 }
5783
5784 unsigned RHSNumProtocols = RHS->getNumProtocols();
5785 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005786 ObjCProtocolDecl **RHSProtocols =
5787 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005788 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5789 if (InheritedProtocolSet.count(RHSProtocols[i]))
5790 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005791 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005792 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005793 Context.CollectInheritedProtocols(RHS->getInterface(),
5794 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005795 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5796 RHSInheritedProtocols.begin(),
5797 E = RHSInheritedProtocols.end(); I != E; ++I)
5798 if (InheritedProtocolSet.count((*I)))
5799 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005800 }
5801}
5802
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005803/// areCommonBaseCompatible - Returns common base class of the two classes if
5804/// one found. Note that this is O'2 algorithm. But it will be called as the
5805/// last type comparison in a ?-exp of ObjC pointer types before a
5806/// warning is issued. So, its invokation is extremely rare.
5807QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005808 const ObjCObjectPointerType *Lptr,
5809 const ObjCObjectPointerType *Rptr) {
5810 const ObjCObjectType *LHS = Lptr->getObjectType();
5811 const ObjCObjectType *RHS = Rptr->getObjectType();
5812 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5813 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005814 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005815 return QualType();
5816
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005817 do {
John McCall8b07ec22010-05-15 11:32:37 +00005818 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005819 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005820 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005821 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5822
5823 QualType Result = QualType(LHS, 0);
5824 if (!Protocols.empty())
5825 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5826 Result = getObjCObjectPointerType(Result);
5827 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005828 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005829 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005830
5831 return QualType();
5832}
5833
John McCall8b07ec22010-05-15 11:32:37 +00005834bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5835 const ObjCObjectType *RHS) {
5836 assert(LHS->getInterface() && "LHS is not an interface type");
5837 assert(RHS->getInterface() && "RHS is not an interface type");
5838
Chris Lattner49af6a42008-04-07 06:51:04 +00005839 // Verify that the base decls are compatible: the RHS must be a subclass of
5840 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005841 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005842 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005843
Chris Lattner49af6a42008-04-07 06:51:04 +00005844 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5845 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005846 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005847 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005848
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005849 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5850 // more detailed analysis is required.
5851 if (RHS->getNumProtocols() == 0) {
5852 // OK, if LHS is a superclass of RHS *and*
5853 // this superclass is assignment compatible with LHS.
5854 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005855 bool IsSuperClass =
5856 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5857 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005858 // OK if conversion of LHS to SuperClass results in narrowing of types
5859 // ; i.e., SuperClass may implement at least one of the protocols
5860 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5861 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5862 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005863 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005864 // If super class has no protocols, it is not a match.
5865 if (SuperClassInheritedProtocols.empty())
5866 return false;
5867
5868 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5869 LHSPE = LHS->qual_end();
5870 LHSPI != LHSPE; LHSPI++) {
5871 bool SuperImplementsProtocol = false;
5872 ObjCProtocolDecl *LHSProto = (*LHSPI);
5873
5874 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5875 SuperClassInheritedProtocols.begin(),
5876 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5877 ObjCProtocolDecl *SuperClassProto = (*I);
5878 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5879 SuperImplementsProtocol = true;
5880 break;
5881 }
5882 }
5883 if (!SuperImplementsProtocol)
5884 return false;
5885 }
5886 return true;
5887 }
5888 return false;
5889 }
Mike Stump11289f42009-09-09 15:08:12 +00005890
John McCall8b07ec22010-05-15 11:32:37 +00005891 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5892 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005893 LHSPI != LHSPE; LHSPI++) {
5894 bool RHSImplementsProtocol = false;
5895
5896 // If the RHS doesn't implement the protocol on the left, the types
5897 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005898 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5899 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005900 RHSPI != RHSPE; RHSPI++) {
5901 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005902 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005903 break;
5904 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005905 }
5906 // FIXME: For better diagnostics, consider passing back the protocol name.
5907 if (!RHSImplementsProtocol)
5908 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005909 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005910 // The RHS implements all protocols listed on the LHS.
5911 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005912}
5913
Steve Naroffb7605152009-02-12 17:52:19 +00005914bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5915 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005916 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5917 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005918
Steve Naroff7cae42b2009-07-10 23:34:53 +00005919 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005920 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005921
5922 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5923 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005924}
5925
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005926bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5927 return canAssignObjCInterfaces(
5928 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5929 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5930}
5931
Mike Stump11289f42009-09-09 15:08:12 +00005932/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005933/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005934/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005935/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005936bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5937 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005938 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005939 return hasSameType(LHS, RHS);
5940
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005941 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005942}
5943
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005944bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005945 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005946}
5947
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005948bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5949 return !mergeTypes(LHS, RHS, true).isNull();
5950}
5951
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005952/// mergeTransparentUnionType - if T is a transparent union type and a member
5953/// of T is compatible with SubType, return the merged type, else return
5954/// QualType()
5955QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5956 bool OfBlockPointer,
5957 bool Unqualified) {
5958 if (const RecordType *UT = T->getAsUnionType()) {
5959 RecordDecl *UD = UT->getDecl();
5960 if (UD->hasAttr<TransparentUnionAttr>()) {
5961 for (RecordDecl::field_iterator it = UD->field_begin(),
5962 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005963 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005964 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5965 if (!MT.isNull())
5966 return MT;
5967 }
5968 }
5969 }
5970
5971 return QualType();
5972}
5973
5974/// mergeFunctionArgumentTypes - merge two types which appear as function
5975/// argument types
5976QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5977 bool OfBlockPointer,
5978 bool Unqualified) {
5979 // GNU extension: two types are compatible if they appear as a function
5980 // argument, one of the types is a transparent union type and the other
5981 // type is compatible with a union member
5982 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5983 Unqualified);
5984 if (!lmerge.isNull())
5985 return lmerge;
5986
5987 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5988 Unqualified);
5989 if (!rmerge.isNull())
5990 return rmerge;
5991
5992 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5993}
5994
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005995QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005996 bool OfBlockPointer,
5997 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005998 const FunctionType *lbase = lhs->getAs<FunctionType>();
5999 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006000 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6001 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006002 bool allLTypes = true;
6003 bool allRTypes = true;
6004
6005 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006006 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006007 if (OfBlockPointer) {
6008 QualType RHS = rbase->getResultType();
6009 QualType LHS = lbase->getResultType();
6010 bool UnqualifiedResult = Unqualified;
6011 if (!UnqualifiedResult)
6012 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006013 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006014 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006015 else
John McCall8c6b56f2010-12-15 01:06:38 +00006016 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6017 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006018 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006019
6020 if (Unqualified)
6021 retType = retType.getUnqualifiedType();
6022
6023 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6024 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6025 if (Unqualified) {
6026 LRetType = LRetType.getUnqualifiedType();
6027 RRetType = RRetType.getUnqualifiedType();
6028 }
6029
6030 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006031 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006032 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006033 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006034
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006035 // FIXME: double check this
6036 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6037 // rbase->getRegParmAttr() != 0 &&
6038 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006039 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6040 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006041
Douglas Gregor8c940862010-01-18 17:14:39 +00006042 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006043 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006044 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006045
John McCall8c6b56f2010-12-15 01:06:38 +00006046 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006047 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6048 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006049 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6050 return QualType();
6051
John McCall31168b02011-06-15 23:02:42 +00006052 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6053 return QualType();
6054
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006055 // functypes which return are preferred over those that do not.
6056 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6057 allLTypes = false;
6058 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6059 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006060 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6061 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006062
John McCall31168b02011-06-15 23:02:42 +00006063 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006064
Eli Friedman47f77112008-08-22 00:56:42 +00006065 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006066 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6067 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006068 unsigned lproto_nargs = lproto->getNumArgs();
6069 unsigned rproto_nargs = rproto->getNumArgs();
6070
6071 // Compatible functions must have the same number of arguments
6072 if (lproto_nargs != rproto_nargs)
6073 return QualType();
6074
6075 // Variadic and non-variadic functions aren't compatible
6076 if (lproto->isVariadic() != rproto->isVariadic())
6077 return QualType();
6078
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006079 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6080 return QualType();
6081
Fariborz Jahanian97676972011-09-28 21:52:05 +00006082 if (LangOpts.ObjCAutoRefCount &&
6083 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6084 return QualType();
6085
Eli Friedman47f77112008-08-22 00:56:42 +00006086 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006087 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006088 for (unsigned i = 0; i < lproto_nargs; i++) {
6089 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6090 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006091 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6092 OfBlockPointer,
6093 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006094 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006095
6096 if (Unqualified)
6097 argtype = argtype.getUnqualifiedType();
6098
Eli Friedman47f77112008-08-22 00:56:42 +00006099 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006100 if (Unqualified) {
6101 largtype = largtype.getUnqualifiedType();
6102 rargtype = rargtype.getUnqualifiedType();
6103 }
6104
Chris Lattner465fa322008-10-05 17:34:18 +00006105 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6106 allLTypes = false;
6107 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6108 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006109 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006110
Eli Friedman47f77112008-08-22 00:56:42 +00006111 if (allLTypes) return lhs;
6112 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006113
6114 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6115 EPI.ExtInfo = einfo;
6116 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006117 }
6118
6119 if (lproto) allRTypes = false;
6120 if (rproto) allLTypes = false;
6121
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006122 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006123 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006124 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006125 if (proto->isVariadic()) return QualType();
6126 // Check that the types are compatible with the types that
6127 // would result from default argument promotions (C99 6.7.5.3p15).
6128 // The only types actually affected are promotable integer
6129 // types and floats, which would be passed as a different
6130 // type depending on whether the prototype is visible.
6131 unsigned proto_nargs = proto->getNumArgs();
6132 for (unsigned i = 0; i < proto_nargs; ++i) {
6133 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006134
6135 // Look at the promotion type of enum types, since that is the type used
6136 // to pass enum values.
6137 if (const EnumType *Enum = argTy->getAs<EnumType>())
6138 argTy = Enum->getDecl()->getPromotionType();
6139
Eli Friedman47f77112008-08-22 00:56:42 +00006140 if (argTy->isPromotableIntegerType() ||
6141 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6142 return QualType();
6143 }
6144
6145 if (allLTypes) return lhs;
6146 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006147
6148 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6149 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006150 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006151 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006152 }
6153
6154 if (allLTypes) return lhs;
6155 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006156 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006157}
6158
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006159QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006160 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006161 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006162 // C++ [expr]: If an expression initially has the type "reference to T", the
6163 // type is adjusted to "T" prior to any further analysis, the expression
6164 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006165 // expression is an lvalue unless the reference is an rvalue reference and
6166 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006167 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6168 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006169
6170 if (Unqualified) {
6171 LHS = LHS.getUnqualifiedType();
6172 RHS = RHS.getUnqualifiedType();
6173 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006174
Eli Friedman47f77112008-08-22 00:56:42 +00006175 QualType LHSCan = getCanonicalType(LHS),
6176 RHSCan = getCanonicalType(RHS);
6177
6178 // If two types are identical, they are compatible.
6179 if (LHSCan == RHSCan)
6180 return LHS;
6181
John McCall8ccfcb52009-09-24 19:53:00 +00006182 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006183 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6184 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006185 if (LQuals != RQuals) {
6186 // If any of these qualifiers are different, we have a type
6187 // mismatch.
6188 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006189 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6190 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006191 return QualType();
6192
6193 // Exactly one GC qualifier difference is allowed: __strong is
6194 // okay if the other type has no GC qualifier but is an Objective
6195 // C object pointer (i.e. implicitly strong by default). We fix
6196 // this by pretending that the unqualified type was actually
6197 // qualified __strong.
6198 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6199 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6200 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6201
6202 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6203 return QualType();
6204
6205 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6206 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6207 }
6208 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6209 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6210 }
Eli Friedman47f77112008-08-22 00:56:42 +00006211 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006212 }
6213
6214 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006215
Eli Friedmandcca6332009-06-01 01:22:52 +00006216 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6217 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006218
Chris Lattnerfd652912008-01-14 05:45:46 +00006219 // We want to consider the two function types to be the same for these
6220 // comparisons, just force one to the other.
6221 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6222 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006223
6224 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006225 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6226 LHSClass = Type::ConstantArray;
6227 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6228 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006229
John McCall8b07ec22010-05-15 11:32:37 +00006230 // ObjCInterfaces are just specialized ObjCObjects.
6231 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6232 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6233
Nate Begemance4d7fc2008-04-18 23:10:10 +00006234 // Canonicalize ExtVector -> Vector.
6235 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6236 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006237
Chris Lattner95554662008-04-07 05:43:21 +00006238 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006239 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006240 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006241 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006242 // Compatibility is based on the underlying type, not the promotion
6243 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006244 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006245 QualType TINT = ETy->getDecl()->getIntegerType();
6246 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006247 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006248 }
John McCall9dd450b2009-09-21 23:43:11 +00006249 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006250 QualType TINT = ETy->getDecl()->getIntegerType();
6251 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006252 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006253 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006254 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006255 if (OfBlockPointer && !BlockReturnType) {
6256 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6257 return LHS;
6258 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6259 return RHS;
6260 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006261
Eli Friedman47f77112008-08-22 00:56:42 +00006262 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006263 }
Eli Friedman47f77112008-08-22 00:56:42 +00006264
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006265 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006266 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006267#define TYPE(Class, Base)
6268#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006269#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006270#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6271#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6272#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006273 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006274
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006275 case Type::LValueReference:
6276 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006277 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006278 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006279
John McCall8b07ec22010-05-15 11:32:37 +00006280 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006281 case Type::IncompleteArray:
6282 case Type::VariableArray:
6283 case Type::FunctionProto:
6284 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006285 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006286
Chris Lattnerfd652912008-01-14 05:45:46 +00006287 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006288 {
6289 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006290 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6291 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006292 if (Unqualified) {
6293 LHSPointee = LHSPointee.getUnqualifiedType();
6294 RHSPointee = RHSPointee.getUnqualifiedType();
6295 }
6296 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6297 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006298 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006299 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006300 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006301 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006302 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006303 return getPointerType(ResultType);
6304 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006305 case Type::BlockPointer:
6306 {
6307 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006308 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6309 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006310 if (Unqualified) {
6311 LHSPointee = LHSPointee.getUnqualifiedType();
6312 RHSPointee = RHSPointee.getUnqualifiedType();
6313 }
6314 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6315 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006316 if (ResultType.isNull()) return QualType();
6317 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6318 return LHS;
6319 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6320 return RHS;
6321 return getBlockPointerType(ResultType);
6322 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006323 case Type::Atomic:
6324 {
6325 // Merge two pointer types, while trying to preserve typedef info
6326 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6327 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6328 if (Unqualified) {
6329 LHSValue = LHSValue.getUnqualifiedType();
6330 RHSValue = RHSValue.getUnqualifiedType();
6331 }
6332 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6333 Unqualified);
6334 if (ResultType.isNull()) return QualType();
6335 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6336 return LHS;
6337 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6338 return RHS;
6339 return getAtomicType(ResultType);
6340 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006341 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006342 {
6343 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6344 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6345 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6346 return QualType();
6347
6348 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6349 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006350 if (Unqualified) {
6351 LHSElem = LHSElem.getUnqualifiedType();
6352 RHSElem = RHSElem.getUnqualifiedType();
6353 }
6354
6355 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006356 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006357 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6358 return LHS;
6359 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6360 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006361 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6362 ArrayType::ArraySizeModifier(), 0);
6363 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6364 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006365 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6366 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006367 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6368 return LHS;
6369 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6370 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006371 if (LVAT) {
6372 // FIXME: This isn't correct! But tricky to implement because
6373 // the array's size has to be the size of LHS, but the type
6374 // has to be different.
6375 return LHS;
6376 }
6377 if (RVAT) {
6378 // FIXME: This isn't correct! But tricky to implement because
6379 // the array's size has to be the size of RHS, but the type
6380 // has to be different.
6381 return RHS;
6382 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006383 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6384 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006385 return getIncompleteArrayType(ResultType,
6386 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006387 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006388 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006389 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006390 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006391 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006392 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006393 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006394 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006395 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006396 case Type::Complex:
6397 // Distinct complex types are incompatible.
6398 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006399 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006400 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006401 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6402 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006403 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006404 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006405 case Type::ObjCObject: {
6406 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006407 // FIXME: This should be type compatibility, e.g. whether
6408 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006409 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6410 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6411 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006412 return LHS;
6413
Eli Friedman47f77112008-08-22 00:56:42 +00006414 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006415 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006416 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006417 if (OfBlockPointer) {
6418 if (canAssignObjCInterfacesInBlockPointer(
6419 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006420 RHS->getAs<ObjCObjectPointerType>(),
6421 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006422 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006423 return QualType();
6424 }
John McCall9dd450b2009-09-21 23:43:11 +00006425 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6426 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006427 return LHS;
6428
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006429 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006430 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006431 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006432
David Blaikie8a40f702012-01-17 06:56:22 +00006433 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006434}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006435
Fariborz Jahanian97676972011-09-28 21:52:05 +00006436bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6437 const FunctionProtoType *FromFunctionType,
6438 const FunctionProtoType *ToFunctionType) {
6439 if (FromFunctionType->hasAnyConsumedArgs() !=
6440 ToFunctionType->hasAnyConsumedArgs())
6441 return false;
6442 FunctionProtoType::ExtProtoInfo FromEPI =
6443 FromFunctionType->getExtProtoInfo();
6444 FunctionProtoType::ExtProtoInfo ToEPI =
6445 ToFunctionType->getExtProtoInfo();
6446 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6447 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6448 ArgIdx != NumArgs; ++ArgIdx) {
6449 if (FromEPI.ConsumedArguments[ArgIdx] !=
6450 ToEPI.ConsumedArguments[ArgIdx])
6451 return false;
6452 }
6453 return true;
6454}
6455
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006456/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6457/// 'RHS' attributes and returns the merged version; including for function
6458/// return types.
6459QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6460 QualType LHSCan = getCanonicalType(LHS),
6461 RHSCan = getCanonicalType(RHS);
6462 // If two types are identical, they are compatible.
6463 if (LHSCan == RHSCan)
6464 return LHS;
6465 if (RHSCan->isFunctionType()) {
6466 if (!LHSCan->isFunctionType())
6467 return QualType();
6468 QualType OldReturnType =
6469 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6470 QualType NewReturnType =
6471 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6472 QualType ResReturnType =
6473 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6474 if (ResReturnType.isNull())
6475 return QualType();
6476 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6477 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6478 // In either case, use OldReturnType to build the new function type.
6479 const FunctionType *F = LHS->getAs<FunctionType>();
6480 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006481 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6482 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006483 QualType ResultType
6484 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006485 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006486 return ResultType;
6487 }
6488 }
6489 return QualType();
6490 }
6491
6492 // If the qualifiers are different, the types can still be merged.
6493 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6494 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6495 if (LQuals != RQuals) {
6496 // If any of these qualifiers are different, we have a type mismatch.
6497 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6498 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6499 return QualType();
6500
6501 // Exactly one GC qualifier difference is allowed: __strong is
6502 // okay if the other type has no GC qualifier but is an Objective
6503 // C object pointer (i.e. implicitly strong by default). We fix
6504 // this by pretending that the unqualified type was actually
6505 // qualified __strong.
6506 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6507 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6508 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6509
6510 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6511 return QualType();
6512
6513 if (GC_L == Qualifiers::Strong)
6514 return LHS;
6515 if (GC_R == Qualifiers::Strong)
6516 return RHS;
6517 return QualType();
6518 }
6519
6520 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6521 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6522 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6523 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6524 if (ResQT == LHSBaseQT)
6525 return LHS;
6526 if (ResQT == RHSBaseQT)
6527 return RHS;
6528 }
6529 return QualType();
6530}
6531
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006532//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006533// Integer Predicates
6534//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006535
Jay Foad39c79802011-01-12 09:06:06 +00006536unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006537 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006538 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006539 if (T->isBooleanType())
6540 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006541 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006542 return (unsigned)getTypeSize(T);
6543}
6544
6545QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006546 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006547
6548 // Turn <4 x signed int> -> <4 x unsigned int>
6549 if (const VectorType *VTy = T->getAs<VectorType>())
6550 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006551 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006552
6553 // For enums, we return the unsigned version of the base type.
6554 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006555 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006556
6557 const BuiltinType *BTy = T->getAs<BuiltinType>();
6558 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006559 switch (BTy->getKind()) {
6560 case BuiltinType::Char_S:
6561 case BuiltinType::SChar:
6562 return UnsignedCharTy;
6563 case BuiltinType::Short:
6564 return UnsignedShortTy;
6565 case BuiltinType::Int:
6566 return UnsignedIntTy;
6567 case BuiltinType::Long:
6568 return UnsignedLongTy;
6569 case BuiltinType::LongLong:
6570 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006571 case BuiltinType::Int128:
6572 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006573 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006574 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006575 }
6576}
6577
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006578ASTMutationListener::~ASTMutationListener() { }
6579
Chris Lattnerecd79c62009-06-14 00:45:47 +00006580
6581//===----------------------------------------------------------------------===//
6582// Builtin Type Computation
6583//===----------------------------------------------------------------------===//
6584
6585/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006586/// pointer over the consumed characters. This returns the resultant type. If
6587/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6588/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6589/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006590///
6591/// RequiresICE is filled in on return to indicate whether the value is required
6592/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006593static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006594 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006595 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006596 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006597 // Modifiers.
6598 int HowLong = 0;
6599 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006600 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006601
Chris Lattnerdc226c22010-10-01 22:42:38 +00006602 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006603 bool Done = false;
6604 while (!Done) {
6605 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006606 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006607 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006608 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006609 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006610 case 'S':
6611 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6612 assert(!Signed && "Can't use 'S' modifier multiple times!");
6613 Signed = true;
6614 break;
6615 case 'U':
6616 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6617 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6618 Unsigned = true;
6619 break;
6620 case 'L':
6621 assert(HowLong <= 2 && "Can't have LLLL modifier");
6622 ++HowLong;
6623 break;
6624 }
6625 }
6626
6627 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006628
Chris Lattnerecd79c62009-06-14 00:45:47 +00006629 // Read the base type.
6630 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006631 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006632 case 'v':
6633 assert(HowLong == 0 && !Signed && !Unsigned &&
6634 "Bad modifiers used with 'v'!");
6635 Type = Context.VoidTy;
6636 break;
6637 case 'f':
6638 assert(HowLong == 0 && !Signed && !Unsigned &&
6639 "Bad modifiers used with 'f'!");
6640 Type = Context.FloatTy;
6641 break;
6642 case 'd':
6643 assert(HowLong < 2 && !Signed && !Unsigned &&
6644 "Bad modifiers used with 'd'!");
6645 if (HowLong)
6646 Type = Context.LongDoubleTy;
6647 else
6648 Type = Context.DoubleTy;
6649 break;
6650 case 's':
6651 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6652 if (Unsigned)
6653 Type = Context.UnsignedShortTy;
6654 else
6655 Type = Context.ShortTy;
6656 break;
6657 case 'i':
6658 if (HowLong == 3)
6659 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6660 else if (HowLong == 2)
6661 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6662 else if (HowLong == 1)
6663 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6664 else
6665 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6666 break;
6667 case 'c':
6668 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6669 if (Signed)
6670 Type = Context.SignedCharTy;
6671 else if (Unsigned)
6672 Type = Context.UnsignedCharTy;
6673 else
6674 Type = Context.CharTy;
6675 break;
6676 case 'b': // boolean
6677 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6678 Type = Context.BoolTy;
6679 break;
6680 case 'z': // size_t.
6681 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6682 Type = Context.getSizeType();
6683 break;
6684 case 'F':
6685 Type = Context.getCFConstantStringType();
6686 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006687 case 'G':
6688 Type = Context.getObjCIdType();
6689 break;
6690 case 'H':
6691 Type = Context.getObjCSelType();
6692 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006693 case 'a':
6694 Type = Context.getBuiltinVaListType();
6695 assert(!Type.isNull() && "builtin va list type not initialized!");
6696 break;
6697 case 'A':
6698 // This is a "reference" to a va_list; however, what exactly
6699 // this means depends on how va_list is defined. There are two
6700 // different kinds of va_list: ones passed by value, and ones
6701 // passed by reference. An example of a by-value va_list is
6702 // x86, where va_list is a char*. An example of by-ref va_list
6703 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6704 // we want this argument to be a char*&; for x86-64, we want
6705 // it to be a __va_list_tag*.
6706 Type = Context.getBuiltinVaListType();
6707 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006708 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006709 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006710 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006711 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006712 break;
6713 case 'V': {
6714 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006715 unsigned NumElements = strtoul(Str, &End, 10);
6716 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006717 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006718
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006719 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6720 RequiresICE, false);
6721 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006722
6723 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006724 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006725 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006726 break;
6727 }
Douglas Gregorfed66992012-06-07 18:08:25 +00006728 case 'E': {
6729 char *End;
6730
6731 unsigned NumElements = strtoul(Str, &End, 10);
6732 assert(End != Str && "Missing vector size");
6733
6734 Str = End;
6735
6736 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6737 false);
6738 Type = Context.getExtVectorType(ElementType, NumElements);
6739 break;
6740 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006741 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006742 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6743 false);
6744 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006745 Type = Context.getComplexType(ElementType);
6746 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006747 }
6748 case 'Y' : {
6749 Type = Context.getPointerDiffType();
6750 break;
6751 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006752 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006753 Type = Context.getFILEType();
6754 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006755 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006756 return QualType();
6757 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006758 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006759 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006760 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006761 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006762 else
6763 Type = Context.getjmp_bufType();
6764
Mike Stump2adb4da2009-07-28 23:47:15 +00006765 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006766 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006767 return QualType();
6768 }
6769 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006770 case 'K':
6771 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6772 Type = Context.getucontext_tType();
6773
6774 if (Type.isNull()) {
6775 Error = ASTContext::GE_Missing_ucontext;
6776 return QualType();
6777 }
6778 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006779 }
Mike Stump11289f42009-09-09 15:08:12 +00006780
Chris Lattnerdc226c22010-10-01 22:42:38 +00006781 // If there are modifiers and if we're allowed to parse them, go for it.
6782 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006783 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006784 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006785 default: Done = true; --Str; break;
6786 case '*':
6787 case '&': {
6788 // Both pointers and references can have their pointee types
6789 // qualified with an address space.
6790 char *End;
6791 unsigned AddrSpace = strtoul(Str, &End, 10);
6792 if (End != Str && AddrSpace != 0) {
6793 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6794 Str = End;
6795 }
6796 if (c == '*')
6797 Type = Context.getPointerType(Type);
6798 else
6799 Type = Context.getLValueReferenceType(Type);
6800 break;
6801 }
6802 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6803 case 'C':
6804 Type = Type.withConst();
6805 break;
6806 case 'D':
6807 Type = Context.getVolatileType(Type);
6808 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006809 case 'R':
6810 Type = Type.withRestrict();
6811 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006812 }
6813 }
Chris Lattner84733392010-10-01 07:13:18 +00006814
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006815 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006816 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006817
Chris Lattnerecd79c62009-06-14 00:45:47 +00006818 return Type;
6819}
6820
6821/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006822QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006823 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006824 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006825 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006826
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006827 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006828
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006829 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006830 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006831 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6832 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006833 if (Error != GE_None)
6834 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006835
6836 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6837
Chris Lattnerecd79c62009-06-14 00:45:47 +00006838 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006839 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006840 if (Error != GE_None)
6841 return QualType();
6842
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006843 // If this argument is required to be an IntegerConstantExpression and the
6844 // caller cares, fill in the bitmask we return.
6845 if (RequiresICE && IntegerConstantArgs)
6846 *IntegerConstantArgs |= 1 << ArgTypes.size();
6847
Chris Lattnerecd79c62009-06-14 00:45:47 +00006848 // Do array -> pointer decay. The builtin should use the decayed type.
6849 if (Ty->isArrayType())
6850 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006851
Chris Lattnerecd79c62009-06-14 00:45:47 +00006852 ArgTypes.push_back(Ty);
6853 }
6854
6855 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6856 "'.' should only occur at end of builtin type list!");
6857
John McCall991eb4b2010-12-21 00:44:39 +00006858 FunctionType::ExtInfo EI;
6859 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6860
6861 bool Variadic = (TypeStr[0] == '.');
6862
6863 // We really shouldn't be making a no-proto type here, especially in C++.
6864 if (ArgTypes.empty() && Variadic)
6865 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006866
John McCalldb40c7f2010-12-14 08:05:40 +00006867 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006868 EPI.ExtInfo = EI;
6869 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006870
6871 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006872}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006873
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006874GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6875 GVALinkage External = GVA_StrongExternal;
6876
6877 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006878 switch (L) {
6879 case NoLinkage:
6880 case InternalLinkage:
6881 case UniqueExternalLinkage:
6882 return GVA_Internal;
6883
6884 case ExternalLinkage:
6885 switch (FD->getTemplateSpecializationKind()) {
6886 case TSK_Undeclared:
6887 case TSK_ExplicitSpecialization:
6888 External = GVA_StrongExternal;
6889 break;
6890
6891 case TSK_ExplicitInstantiationDefinition:
6892 return GVA_ExplicitTemplateInstantiation;
6893
6894 case TSK_ExplicitInstantiationDeclaration:
6895 case TSK_ImplicitInstantiation:
6896 External = GVA_TemplateInstantiation;
6897 break;
6898 }
6899 }
6900
6901 if (!FD->isInlined())
6902 return External;
6903
David Blaikiebbafb8a2012-03-11 07:00:24 +00006904 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006905 // GNU or C99 inline semantics. Determine whether this symbol should be
6906 // externally visible.
6907 if (FD->isInlineDefinitionExternallyVisible())
6908 return External;
6909
6910 // C99 inline semantics, where the symbol is not externally visible.
6911 return GVA_C99Inline;
6912 }
6913
6914 // C++0x [temp.explicit]p9:
6915 // [ Note: The intent is that an inline function that is the subject of
6916 // an explicit instantiation declaration will still be implicitly
6917 // instantiated when used so that the body can be considered for
6918 // inlining, but that no out-of-line copy of the inline function would be
6919 // generated in the translation unit. -- end note ]
6920 if (FD->getTemplateSpecializationKind()
6921 == TSK_ExplicitInstantiationDeclaration)
6922 return GVA_C99Inline;
6923
6924 return GVA_CXXInline;
6925}
6926
6927GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6928 // If this is a static data member, compute the kind of template
6929 // specialization. Otherwise, this variable is not part of a
6930 // template.
6931 TemplateSpecializationKind TSK = TSK_Undeclared;
6932 if (VD->isStaticDataMember())
6933 TSK = VD->getTemplateSpecializationKind();
6934
6935 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006936 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006937 VD->getType()->getLinkage() == UniqueExternalLinkage)
6938 L = UniqueExternalLinkage;
6939
6940 switch (L) {
6941 case NoLinkage:
6942 case InternalLinkage:
6943 case UniqueExternalLinkage:
6944 return GVA_Internal;
6945
6946 case ExternalLinkage:
6947 switch (TSK) {
6948 case TSK_Undeclared:
6949 case TSK_ExplicitSpecialization:
6950 return GVA_StrongExternal;
6951
6952 case TSK_ExplicitInstantiationDeclaration:
6953 llvm_unreachable("Variable should not be instantiated");
6954 // Fall through to treat this like any other instantiation.
6955
6956 case TSK_ExplicitInstantiationDefinition:
6957 return GVA_ExplicitTemplateInstantiation;
6958
6959 case TSK_ImplicitInstantiation:
6960 return GVA_TemplateInstantiation;
6961 }
6962 }
6963
David Blaikie8a40f702012-01-17 06:56:22 +00006964 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006965}
6966
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006967bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006968 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6969 if (!VD->isFileVarDecl())
6970 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006971 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006972 return false;
6973
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006974 // Weak references don't produce any output by themselves.
6975 if (D->hasAttr<WeakRefAttr>())
6976 return false;
6977
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006978 // Aliases and used decls are required.
6979 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6980 return true;
6981
6982 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6983 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006984 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006985 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006986
6987 // Constructors and destructors are required.
6988 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6989 return true;
6990
6991 // The key function for a class is required.
6992 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6993 const CXXRecordDecl *RD = MD->getParent();
6994 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6995 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6996 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6997 return true;
6998 }
6999 }
7000
7001 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7002
7003 // static, static inline, always_inline, and extern inline functions can
7004 // always be deferred. Normal inline functions can be deferred in C99/C++.
7005 // Implicit template instantiations can also be deferred in C++.
7006 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007007 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007008 return false;
7009 return true;
7010 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007011
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007012 const VarDecl *VD = cast<VarDecl>(D);
7013 assert(VD->isFileVarDecl() && "Expected file scoped var");
7014
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007015 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7016 return false;
7017
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007018 // Structs that have non-trivial constructors or destructors are required.
7019
7020 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007021 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007022 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7023 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007024 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7025 RD->hasTrivialCopyConstructor() &&
7026 RD->hasTrivialMoveConstructor() &&
7027 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007028 return true;
7029 }
7030 }
7031
7032 GVALinkage L = GetGVALinkageForVariable(VD);
7033 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7034 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7035 return false;
7036 }
7037
7038 return true;
7039}
Charles Davis53c59df2010-08-16 03:33:14 +00007040
Charles Davis99202b32010-11-09 18:04:24 +00007041CallingConv ASTContext::getDefaultMethodCallConv() {
7042 // Pass through to the C++ ABI object
7043 return ABI->getDefaultMethodCallConv();
7044}
7045
Jay Foad39c79802011-01-12 09:06:06 +00007046bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007047 // Pass through to the C++ ABI object
7048 return ABI->isNearlyEmpty(RD);
7049}
7050
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007051MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007052 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007053 case CXXABI_ARM:
7054 case CXXABI_Itanium:
7055 return createItaniumMangleContext(*this, getDiagnostics());
7056 case CXXABI_Microsoft:
7057 return createMicrosoftMangleContext(*this, getDiagnostics());
7058 }
David Blaikie83d382b2011-09-23 05:06:16 +00007059 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007060}
7061
Charles Davis53c59df2010-08-16 03:33:14 +00007062CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007063
7064size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007065 return ASTRecordLayouts.getMemorySize()
7066 + llvm::capacity_in_bytes(ObjCLayouts)
7067 + llvm::capacity_in_bytes(KeyFunctions)
7068 + llvm::capacity_in_bytes(ObjCImpls)
7069 + llvm::capacity_in_bytes(BlockVarCopyInits)
7070 + llvm::capacity_in_bytes(DeclAttrs)
7071 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7072 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7073 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7074 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7075 + llvm::capacity_in_bytes(OverriddenMethods)
7076 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007077 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007078 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007079}
Ted Kremenek540017e2011-10-06 05:00:56 +00007080
Douglas Gregor63798542012-02-20 19:44:39 +00007081unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7082 CXXRecordDecl *Lambda = CallOperator->getParent();
7083 return LambdaMangleContexts[Lambda->getDeclContext()]
7084 .getManglingNumber(CallOperator);
7085}
7086
7087
Ted Kremenek540017e2011-10-06 05:00:56 +00007088void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7089 ParamIndices[D] = index;
7090}
7091
7092unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7093 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7094 assert(I != ParamIndices.end() &&
7095 "ParmIndices lacks entry set by ParmVarDecl");
7096 return I->second;
7097}