blob: 42a5fa37b1b5fdcaf6940fb41acee05872282323 [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"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000016#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000017#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000020#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000021#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000023#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000024#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000025#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000026#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000028#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000029#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000030#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000031#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000032#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000033#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000034#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000035#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000036#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000037
Chris Lattnerddc135e2006-11-10 06:34:16 +000038using namespace clang;
39
Douglas Gregor9672f922010-07-03 00:47:00 +000040unsigned ASTContext::NumImplicitDefaultConstructors;
41unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000042unsigned ASTContext::NumImplicitCopyConstructors;
43unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000044unsigned ASTContext::NumImplicitMoveConstructors;
45unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000046unsigned ASTContext::NumImplicitCopyAssignmentOperators;
47unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveAssignmentOperators;
49unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000050unsigned ASTContext::NumImplicitDestructors;
51unsigned ASTContext::NumImplicitDestructorsDeclared;
52
Steve Naroff0af91202007-04-27 21:51:21 +000053enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000054 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000055};
56
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000057RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000058 if (!CommentsLoaded && ExternalSource) {
59 ExternalSource->ReadComments();
60 CommentsLoaded = true;
61 }
62
63 assert(D);
64
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000065 // User can not attach documentation to implicit declarations.
66 if (D->isImplicit())
67 return NULL;
68
Dmitri Gribenkob2610882012-08-14 17:17:18 +000069 // User can not attach documentation to implicit instantiations.
70 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
71 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
72 return NULL;
73 }
74
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000075 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
76 if (VD->isStaticDataMember() &&
77 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
78 return NULL;
79 }
80
81 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
82 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
83 return NULL;
84 }
85
86 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
87 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 return NULL;
89 }
90
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000091 // TODO: handle comments for function parameters properly.
92 if (isa<ParmVarDecl>(D))
93 return NULL;
94
Dmitri Gribenko34df2202012-07-31 22:37:06 +000095 // TODO: we could look up template parameter documentation in the template
96 // documentation.
97 if (isa<TemplateTypeParmDecl>(D) ||
98 isa<NonTypeTemplateParmDecl>(D) ||
99 isa<TemplateTemplateParmDecl>(D))
100 return NULL;
101
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000102 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000103
104 // If there are no comments anywhere, we won't find anything.
105 if (RawComments.empty())
106 return NULL;
107
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000108 // Find declaration location.
109 // For Objective-C declarations we generally don't expect to have multiple
110 // declarators, thus use declaration starting location as the "declaration
111 // location".
112 // For all other declarations multiple declarators are used quite frequently,
113 // so we use the location of the identifier as the "declaration location".
114 SourceLocation DeclLoc;
115 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000116 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000117 isa<RedeclarableTemplateDecl>(D) ||
118 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000119 DeclLoc = D->getLocStart();
120 else
121 DeclLoc = D->getLocation();
122
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000123 // If the declaration doesn't map directly to a location in a file, we
124 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000125 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
126 return NULL;
127
128 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000129 ArrayRef<RawComment *>::iterator Comment;
130 {
131 // When searching for comments during parsing, the comment we are looking
132 // for is usually among the last two comments we parsed -- check them
133 // first.
134 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
135 BeforeThanCompare<RawComment> Compare(SourceMgr);
136 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
137 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
138 if (!Found && RawComments.size() >= 2) {
139 MaybeBeforeDecl--;
140 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
141 }
142
143 if (Found) {
144 Comment = MaybeBeforeDecl + 1;
145 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
146 &CommentAtDeclLoc, Compare));
147 } else {
148 // Slow path.
149 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
150 &CommentAtDeclLoc, Compare);
151 }
152 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000153
154 // Decompose the location for the declaration and find the beginning of the
155 // file buffer.
156 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
157
158 // First check whether we have a trailing comment.
159 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000160 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000161 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000162 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000163 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000164 // Check that Doxygen trailing comment comes after the declaration, starts
165 // on the same line and in the same file as the declaration.
166 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
167 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
168 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
169 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000170 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171 }
172 }
173
174 // The comment just after the declaration was not a trailing comment.
175 // Let's look at the previous comment.
176 if (Comment == RawComments.begin())
177 return NULL;
178 --Comment;
179
180 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000181 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000182 return NULL;
183
184 // Decompose the end of the comment.
185 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000186 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000187
188 // If the comment and the declaration aren't in the same file, then they
189 // aren't related.
190 if (DeclLocDecomp.first != CommentEndDecomp.first)
191 return NULL;
192
193 // Get the corresponding buffer.
194 bool Invalid = false;
195 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
196 &Invalid).data();
197 if (Invalid)
198 return NULL;
199
200 // Extract text between the comment and declaration.
201 StringRef Text(Buffer + CommentEndDecomp.second,
202 DeclLocDecomp.second - CommentEndDecomp.second);
203
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000204 // There should be no other declarations or preprocessor directives between
205 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000206 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000207 return NULL;
208
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000209 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000210}
211
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000212namespace {
213/// If we have a 'templated' declaration for a template, adjust 'D' to
214/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000215/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000216const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000217 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000218 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000219 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000220 return FTD;
221
222 // Nothing to do if function is not an implicit instantiation.
223 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
224 return D;
225
226 // Function is an implicit instantiation of a function template?
227 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
228 return FTD;
229
230 // Function is instantiated from a member definition of a class template?
231 if (const FunctionDecl *MemberDecl =
232 FD->getInstantiatedFromMemberFunction())
233 return MemberDecl;
234
235 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000236 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000237 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
238 // Static data member is instantiated from a member definition of a class
239 // template?
240 if (VD->isStaticDataMember())
241 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
242 return MemberDecl;
243
244 return D;
245 }
246 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
247 // Is this class declaration part of a class template?
248 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
249 return CTD;
250
251 // Class is an implicit instantiation of a class template or partial
252 // specialization?
253 if (const ClassTemplateSpecializationDecl *CTSD =
254 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
255 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
256 return D;
257 llvm::PointerUnion<ClassTemplateDecl *,
258 ClassTemplatePartialSpecializationDecl *>
259 PU = CTSD->getSpecializedTemplateOrPartial();
260 return PU.is<ClassTemplateDecl*>() ?
261 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
262 static_cast<const Decl*>(
263 PU.get<ClassTemplatePartialSpecializationDecl *>());
264 }
265
266 // Class is instantiated from a member definition of a class template?
267 if (const MemberSpecializationInfo *Info =
268 CRD->getMemberSpecializationInfo())
269 return Info->getInstantiatedFrom();
270
271 return D;
272 }
273 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
274 // Enum is instantiated from a member definition of a class template?
275 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
276 return MemberDecl;
277
278 return D;
279 }
280 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000281 return D;
282}
283} // unnamed namespace
284
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000285const RawComment *ASTContext::getRawCommentForAnyRedecl(
286 const Decl *D,
287 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000288 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000289
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000290 // Check whether we have cached a comment for this declaration already.
291 {
292 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
293 RedeclComments.find(D);
294 if (Pos != RedeclComments.end()) {
295 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000296 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
297 if (OriginalDecl)
298 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000299 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000300 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000301 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000302 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000303
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000304 // Search for comments attached to declarations in the redeclaration chain.
305 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000306 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000307 for (Decl::redecl_iterator I = D->redecls_begin(),
308 E = D->redecls_end();
309 I != E; ++I) {
310 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
311 RedeclComments.find(*I);
312 if (Pos != RedeclComments.end()) {
313 const RawCommentAndCacheFlags &Raw = Pos->second;
314 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
315 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000316 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000317 break;
318 }
319 } else {
320 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000321 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000322 RawCommentAndCacheFlags Raw;
323 if (RC) {
324 Raw.setRaw(RC);
325 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
326 } else
327 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000328 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000329 RedeclComments[*I] = Raw;
330 if (RC)
331 break;
332 }
333 }
334
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000335 // If we found a comment, it should be a documentation comment.
336 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000338 if (OriginalDecl)
339 *OriginalDecl = OriginalDeclForRC;
340
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000341 // Update cache for every declaration in the redeclaration chain.
342 RawCommentAndCacheFlags Raw;
343 Raw.setRaw(RC);
344 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000345 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346
347 for (Decl::redecl_iterator I = D->redecls_begin(),
348 E = D->redecls_end();
349 I != E; ++I) {
350 RawCommentAndCacheFlags &R = RedeclComments[*I];
351 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
352 R = Raw;
353 }
354
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000355 return RC;
356}
357
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000358comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000359 D = adjustDeclToTemplate(D);
360 const Decl *Canonical = D->getCanonicalDecl();
361 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
362 ParsedComments.find(Canonical);
363 if (Pos != ParsedComments.end())
364 return Pos->second;
365
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000366 const Decl *OriginalDecl;
367 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000368 if (!RC)
369 return NULL;
370
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000371 // If the RawComment was attached to other redeclaration of this Decl, we
372 // should parse the comment in context of that other Decl. This is important
373 // because comments can contain references to parameter names which can be
374 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000375 if (D != OriginalDecl)
376 return getCommentForDecl(OriginalDecl);
377
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000378 comments::FullComment *FC = RC->parse(*this, D);
379 ParsedComments[Canonical] = FC;
380 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000381}
382
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000383void
384ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
385 TemplateTemplateParmDecl *Parm) {
386 ID.AddInteger(Parm->getDepth());
387 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000388 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000389
390 TemplateParameterList *Params = Parm->getTemplateParameters();
391 ID.AddInteger(Params->size());
392 for (TemplateParameterList::const_iterator P = Params->begin(),
393 PEnd = Params->end();
394 P != PEnd; ++P) {
395 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
396 ID.AddInteger(0);
397 ID.AddBoolean(TTP->isParameterPack());
398 continue;
399 }
400
401 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
402 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000403 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000404 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000405 if (NTTP->isExpandedParameterPack()) {
406 ID.AddBoolean(true);
407 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000408 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
409 QualType T = NTTP->getExpansionType(I);
410 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
411 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000412 } else
413 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000414 continue;
415 }
416
417 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
418 ID.AddInteger(2);
419 Profile(ID, TTP);
420 }
421}
422
423TemplateTemplateParmDecl *
424ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000425 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000426 // Check if we already have a canonical template template parameter.
427 llvm::FoldingSetNodeID ID;
428 CanonicalTemplateTemplateParm::Profile(ID, TTP);
429 void *InsertPos = 0;
430 CanonicalTemplateTemplateParm *Canonical
431 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
432 if (Canonical)
433 return Canonical->getParam();
434
435 // Build a canonical template parameter list.
436 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000437 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000438 CanonParams.reserve(Params->size());
439 for (TemplateParameterList::const_iterator P = Params->begin(),
440 PEnd = Params->end();
441 P != PEnd; ++P) {
442 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
443 CanonParams.push_back(
444 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000445 SourceLocation(),
446 SourceLocation(),
447 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000448 TTP->getIndex(), 0, false,
449 TTP->isParameterPack()));
450 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000451 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
452 QualType T = getCanonicalType(NTTP->getType());
453 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
454 NonTypeTemplateParmDecl *Param;
455 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000456 SmallVector<QualType, 2> ExpandedTypes;
457 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000458 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
459 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
460 ExpandedTInfos.push_back(
461 getTrivialTypeSourceInfo(ExpandedTypes.back()));
462 }
463
464 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000465 SourceLocation(),
466 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000467 NTTP->getDepth(),
468 NTTP->getPosition(), 0,
469 T,
470 TInfo,
471 ExpandedTypes.data(),
472 ExpandedTypes.size(),
473 ExpandedTInfos.data());
474 } else {
475 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000476 SourceLocation(),
477 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000478 NTTP->getDepth(),
479 NTTP->getPosition(), 0,
480 T,
481 NTTP->isParameterPack(),
482 TInfo);
483 }
484 CanonParams.push_back(Param);
485
486 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000487 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
488 cast<TemplateTemplateParmDecl>(*P)));
489 }
490
491 TemplateTemplateParmDecl *CanonTTP
492 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
493 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000494 TTP->getPosition(),
495 TTP->isParameterPack(),
496 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000497 TemplateParameterList::Create(*this, SourceLocation(),
498 SourceLocation(),
499 CanonParams.data(),
500 CanonParams.size(),
501 SourceLocation()));
502
503 // Get the new insert position for the node we care about.
504 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
505 assert(Canonical == 0 && "Shouldn't be in the map!");
506 (void)Canonical;
507
508 // Create the canonical template template parameter entry.
509 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
510 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
511 return CanonTTP;
512}
513
Charles Davis53c59df2010-08-16 03:33:14 +0000514CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000515 if (!LangOpts.CPlusPlus) return 0;
516
Charles Davis6bcb07a2010-08-19 02:18:14 +0000517 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000518 case CXXABI_ARM:
519 return CreateARMCXXABI(*this);
520 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000521 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000522 case CXXABI_Microsoft:
523 return CreateMicrosoftCXXABI(*this);
524 }
David Blaikie8a40f702012-01-17 06:56:22 +0000525 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000526}
527
Douglas Gregore8bbc122011-09-02 00:18:52 +0000528static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000529 const LangOptions &LOpts) {
530 if (LOpts.FakeAddressSpaceMap) {
531 // The fake address space map must have a distinct entry for each
532 // language-specific address space.
533 static const unsigned FakeAddrSpaceMap[] = {
534 1, // opencl_global
535 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000536 3, // opencl_constant
537 4, // cuda_device
538 5, // cuda_constant
539 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000540 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000541 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000542 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000543 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000544 }
545}
546
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000547ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000548 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000549 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000550 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000551 unsigned size_reserve,
552 bool DelayInitialization)
553 : FunctionProtoTypes(this_()),
554 TemplateSpecializationTypes(this_()),
555 DependentTemplateSpecializationTypes(this_()),
556 SubstTemplateTemplateParmPacks(this_()),
557 GlobalNestedNameSpecifier(0),
558 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000559 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000560 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000561 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000562 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000563 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000564 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
565 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
566 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000567 NullTypeSourceInfo(QualType()),
568 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000569 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000570 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000571 Idents(idents), Selectors(sels),
572 BuiltinInfo(builtins),
573 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000574 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000575 Comments(SM), CommentsLoaded(false),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000576 LastSDM(0, 0),
577 UniqueBlockByRefTypeID(0)
578{
Mike Stump11289f42009-09-09 15:08:12 +0000579 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000580 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000581
582 if (!DelayInitialization) {
583 assert(t && "No target supplied for ASTContext initialization");
584 InitBuiltinTypes(*t);
585 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000586}
587
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000588ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000589 // Release the DenseMaps associated with DeclContext objects.
590 // FIXME: Is this the ideal solution?
591 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000592
Douglas Gregor5b11d492010-07-25 17:53:33 +0000593 // Call all of the deallocation functions.
594 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
595 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000596
Ted Kremenek076baeb2010-06-08 23:00:58 +0000597 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000598 // because they can contain DenseMaps.
599 for (llvm::DenseMap<const ObjCContainerDecl*,
600 const ASTRecordLayout*>::iterator
601 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
602 // Increment in loop to prevent using deallocated memory.
603 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
604 R->Destroy(*this);
605
Ted Kremenek076baeb2010-06-08 23:00:58 +0000606 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
607 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
608 // Increment in loop to prevent using deallocated memory.
609 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
610 R->Destroy(*this);
611 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000612
613 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
614 AEnd = DeclAttrs.end();
615 A != AEnd; ++A)
616 A->second->~AttrVec();
617}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000618
Douglas Gregor1a809332010-05-23 18:26:36 +0000619void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
620 Deallocations.push_back(std::make_pair(Callback, Data));
621}
622
Mike Stump11289f42009-09-09 15:08:12 +0000623void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000624ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000625 ExternalSource.reset(Source.take());
626}
627
Chris Lattner4eb445d2007-01-26 01:27:23 +0000628void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000629 llvm::errs() << "\n*** AST Context Stats:\n";
630 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000631
Douglas Gregora30d0462009-05-26 14:40:08 +0000632 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000633#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000634#define ABSTRACT_TYPE(Name, Parent)
635#include "clang/AST/TypeNodes.def"
636 0 // Extra
637 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000638
Chris Lattner4eb445d2007-01-26 01:27:23 +0000639 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
640 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000641 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000642 }
643
Douglas Gregora30d0462009-05-26 14:40:08 +0000644 unsigned Idx = 0;
645 unsigned TotalBytes = 0;
646#define TYPE(Name, Parent) \
647 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000648 llvm::errs() << " " << counts[Idx] << " " << #Name \
649 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000650 TotalBytes += counts[Idx] * sizeof(Name##Type); \
651 ++Idx;
652#define ABSTRACT_TYPE(Name, Parent)
653#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000654
Chandler Carruth3c147a72011-07-04 05:32:14 +0000655 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
656
Douglas Gregor7454c562010-07-02 20:37:36 +0000657 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000658 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
659 << NumImplicitDefaultConstructors
660 << " implicit default constructors created\n";
661 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
662 << NumImplicitCopyConstructors
663 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000664 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000665 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
666 << NumImplicitMoveConstructors
667 << " implicit move constructors created\n";
668 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
669 << NumImplicitCopyAssignmentOperators
670 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000671 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000672 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
673 << NumImplicitMoveAssignmentOperators
674 << " implicit move assignment operators created\n";
675 llvm::errs() << NumImplicitDestructorsDeclared << "/"
676 << NumImplicitDestructors
677 << " implicit destructors created\n";
678
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000679 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000680 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000681 ExternalSource->PrintStats();
682 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000683
Douglas Gregor5b11d492010-07-25 17:53:33 +0000684 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000685}
686
Douglas Gregor801c99d2011-08-12 06:49:56 +0000687TypedefDecl *ASTContext::getInt128Decl() const {
688 if (!Int128Decl) {
689 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
690 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
691 getTranslationUnitDecl(),
692 SourceLocation(),
693 SourceLocation(),
694 &Idents.get("__int128_t"),
695 TInfo);
696 }
697
698 return Int128Decl;
699}
700
701TypedefDecl *ASTContext::getUInt128Decl() const {
702 if (!UInt128Decl) {
703 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
704 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
705 getTranslationUnitDecl(),
706 SourceLocation(),
707 SourceLocation(),
708 &Idents.get("__uint128_t"),
709 TInfo);
710 }
711
712 return UInt128Decl;
713}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000714
John McCall48f2d582009-10-23 23:03:21 +0000715void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000716 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000717 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000718 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000719}
720
Douglas Gregore8bbc122011-09-02 00:18:52 +0000721void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
722 assert((!this->Target || this->Target == &Target) &&
723 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000724 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000725
Douglas Gregore8bbc122011-09-02 00:18:52 +0000726 this->Target = &Target;
727
728 ABI.reset(createCXXABI(Target));
729 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
730
Chris Lattner970e54e2006-11-12 00:37:36 +0000731 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000732 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000733
Chris Lattner970e54e2006-11-12 00:37:36 +0000734 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000735 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000736 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000737 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000738 InitBuiltinType(CharTy, BuiltinType::Char_S);
739 else
740 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000741 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000742 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
743 InitBuiltinType(ShortTy, BuiltinType::Short);
744 InitBuiltinType(IntTy, BuiltinType::Int);
745 InitBuiltinType(LongTy, BuiltinType::Long);
746 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000747
Chris Lattner970e54e2006-11-12 00:37:36 +0000748 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000749 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
750 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
751 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
752 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
753 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000754
Chris Lattner970e54e2006-11-12 00:37:36 +0000755 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000756 InitBuiltinType(FloatTy, BuiltinType::Float);
757 InitBuiltinType(DoubleTy, BuiltinType::Double);
758 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000759
Chris Lattnerf122cef2009-04-30 02:43:43 +0000760 // GNU extension, 128-bit integers.
761 InitBuiltinType(Int128Ty, BuiltinType::Int128);
762 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
763
Chris Lattnerad3467e2010-12-25 23:25:43 +0000764 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000765 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000766 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
767 else // -fshort-wchar makes wchar_t be unsigned.
768 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
769 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000770 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000771
James Molloy36365542012-05-04 10:55:22 +0000772 WIntTy = getFromTargetType(Target.getWIntType());
773
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000774 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
775 InitBuiltinType(Char16Ty, BuiltinType::Char16);
776 else // C99
777 Char16Ty = getFromTargetType(Target.getChar16Type());
778
779 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
780 InitBuiltinType(Char32Ty, BuiltinType::Char32);
781 else // C99
782 Char32Ty = getFromTargetType(Target.getChar32Type());
783
Douglas Gregor4619e432008-12-05 23:32:09 +0000784 // Placeholder type for type-dependent expressions whose type is
785 // completely unknown. No code should ever check a type against
786 // DependentTy and users should never see it; however, it is here to
787 // help diagnose failures to properly check for type-dependent
788 // expressions.
789 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000790
John McCall36e7fe32010-10-12 00:20:44 +0000791 // Placeholder type for functions.
792 InitBuiltinType(OverloadTy, BuiltinType::Overload);
793
John McCall0009fcc2011-04-26 20:42:42 +0000794 // Placeholder type for bound members.
795 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
796
John McCall526ab472011-10-25 17:37:35 +0000797 // Placeholder type for pseudo-objects.
798 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
799
John McCall31996342011-04-07 08:22:57 +0000800 // "any" type; useful for debugger-like clients.
801 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
802
John McCall8a6b59a2011-10-17 18:09:15 +0000803 // Placeholder type for unbridged ARC casts.
804 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
805
Chris Lattner970e54e2006-11-12 00:37:36 +0000806 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000807 FloatComplexTy = getComplexType(FloatTy);
808 DoubleComplexTy = getComplexType(DoubleTy);
809 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000810
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000811 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000812 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
813 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000814 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000815
816 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000817 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
818 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000819
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000820 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000821
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000822 // void * type
823 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000824
825 // nullptr type (C++0x 2.14.7)
826 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000827
828 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
829 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000830
831 // Builtin type used to help define __builtin_va_list.
832 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000833}
834
David Blaikie9c902b52011-09-25 23:23:43 +0000835DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000836 return SourceMgr.getDiagnostics();
837}
838
Douglas Gregor561eceb2010-08-30 16:49:28 +0000839AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
840 AttrVec *&Result = DeclAttrs[D];
841 if (!Result) {
842 void *Mem = Allocate(sizeof(AttrVec));
843 Result = new (Mem) AttrVec;
844 }
845
846 return *Result;
847}
848
849/// \brief Erase the attributes corresponding to the given declaration.
850void ASTContext::eraseDeclAttrs(const Decl *D) {
851 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
852 if (Pos != DeclAttrs.end()) {
853 Pos->second->~AttrVec();
854 DeclAttrs.erase(Pos);
855 }
856}
857
Douglas Gregor86d142a2009-10-08 07:24:58 +0000858MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000859ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000860 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000861 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000862 = InstantiatedFromStaticDataMember.find(Var);
863 if (Pos == InstantiatedFromStaticDataMember.end())
864 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000865
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000866 return Pos->second;
867}
868
Mike Stump11289f42009-09-09 15:08:12 +0000869void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000870ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000871 TemplateSpecializationKind TSK,
872 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000873 assert(Inst->isStaticDataMember() && "Not a static data member");
874 assert(Tmpl->isStaticDataMember() && "Not a static data member");
875 assert(!InstantiatedFromStaticDataMember[Inst] &&
876 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000877 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000878 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000879}
880
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000881FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
882 const FunctionDecl *FD){
883 assert(FD && "Specialization is 0");
884 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000885 = ClassScopeSpecializationPattern.find(FD);
886 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000887 return 0;
888
889 return Pos->second;
890}
891
892void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
893 FunctionDecl *Pattern) {
894 assert(FD && "Specialization is 0");
895 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000896 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000897}
898
John McCalle61f2ba2009-11-18 02:36:19 +0000899NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000900ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000901 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000902 = InstantiatedFromUsingDecl.find(UUD);
903 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000904 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000905
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000906 return Pos->second;
907}
908
909void
John McCallb96ec562009-12-04 22:46:56 +0000910ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
911 assert((isa<UsingDecl>(Pattern) ||
912 isa<UnresolvedUsingValueDecl>(Pattern) ||
913 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
914 "pattern decl is not a using decl");
915 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
916 InstantiatedFromUsingDecl[Inst] = Pattern;
917}
918
919UsingShadowDecl *
920ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
921 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
922 = InstantiatedFromUsingShadowDecl.find(Inst);
923 if (Pos == InstantiatedFromUsingShadowDecl.end())
924 return 0;
925
926 return Pos->second;
927}
928
929void
930ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
931 UsingShadowDecl *Pattern) {
932 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
933 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000934}
935
Anders Carlsson5da84842009-09-01 04:26:58 +0000936FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
937 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
938 = InstantiatedFromUnnamedFieldDecl.find(Field);
939 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
940 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000941
Anders Carlsson5da84842009-09-01 04:26:58 +0000942 return Pos->second;
943}
944
945void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
946 FieldDecl *Tmpl) {
947 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
948 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
949 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
950 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000951
Anders Carlsson5da84842009-09-01 04:26:58 +0000952 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
953}
954
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000955bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
956 const FieldDecl *LastFD) const {
957 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000958 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000959}
960
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000961bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
962 const FieldDecl *LastFD) const {
963 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000964 FD->getBitWidthValue(*this) == 0 &&
965 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000966}
967
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000968bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
969 const FieldDecl *LastFD) const {
970 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000971 FD->getBitWidthValue(*this) &&
972 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000973}
974
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000975bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000976 const FieldDecl *LastFD) const {
977 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000978 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000979}
980
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000981bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000982 const FieldDecl *LastFD) const {
983 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000984 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000985}
986
Douglas Gregor832940b2010-03-02 23:58:15 +0000987ASTContext::overridden_cxx_method_iterator
988ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
989 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
990 = OverriddenMethods.find(Method);
991 if (Pos == OverriddenMethods.end())
992 return 0;
993
994 return Pos->second.begin();
995}
996
997ASTContext::overridden_cxx_method_iterator
998ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
999 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1000 = OverriddenMethods.find(Method);
1001 if (Pos == OverriddenMethods.end())
1002 return 0;
1003
1004 return Pos->second.end();
1005}
1006
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001007unsigned
1008ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1009 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1010 = OverriddenMethods.find(Method);
1011 if (Pos == OverriddenMethods.end())
1012 return 0;
1013
1014 return Pos->second.size();
1015}
1016
Douglas Gregor832940b2010-03-02 23:58:15 +00001017void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1018 const CXXMethodDecl *Overridden) {
1019 OverriddenMethods[Method].push_back(Overridden);
1020}
1021
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001022void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1023 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1024 assert(!Import->isFromASTFile() && "Non-local import declaration");
1025 if (!FirstLocalImport) {
1026 FirstLocalImport = Import;
1027 LastLocalImport = Import;
1028 return;
1029 }
1030
1031 LastLocalImport->NextLocalImport = Import;
1032 LastLocalImport = Import;
1033}
1034
Chris Lattner53cfe802007-07-18 17:52:12 +00001035//===----------------------------------------------------------------------===//
1036// Type Sizing and Analysis
1037//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001038
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001039/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1040/// scalar floating point type.
1041const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001042 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001043 assert(BT && "Not a floating point type!");
1044 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001045 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001046 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001047 case BuiltinType::Float: return Target->getFloatFormat();
1048 case BuiltinType::Double: return Target->getDoubleFormat();
1049 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001050 }
1051}
1052
Ken Dyck160146e2010-01-27 17:10:57 +00001053/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001054/// specified decl. Note that bitfields do not have a valid alignment, so
1055/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001056/// If @p RefAsPointee, references are treated like their underlying type
1057/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001058CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001059 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001060
John McCall94268702010-10-08 18:24:19 +00001061 bool UseAlignAttrOnly = false;
1062 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1063 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001064
John McCall94268702010-10-08 18:24:19 +00001065 // __attribute__((aligned)) can increase or decrease alignment
1066 // *except* on a struct or struct member, where it only increases
1067 // alignment unless 'packed' is also specified.
1068 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001069 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001070 // ignore that possibility; Sema should diagnose it.
1071 if (isa<FieldDecl>(D)) {
1072 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1073 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1074 } else {
1075 UseAlignAttrOnly = true;
1076 }
1077 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001078 else if (isa<FieldDecl>(D))
1079 UseAlignAttrOnly =
1080 D->hasAttr<PackedAttr>() ||
1081 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001082
John McCall4e819612011-01-20 07:57:12 +00001083 // If we're using the align attribute only, just ignore everything
1084 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001085 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001086 // do nothing
1087
John McCall94268702010-10-08 18:24:19 +00001088 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001089 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001090 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001091 if (RefAsPointee)
1092 T = RT->getPointeeType();
1093 else
1094 T = getPointerType(RT->getPointeeType());
1095 }
1096 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001097 // Adjust alignments of declarations with array type by the
1098 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001099 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001100 const ArrayType *arrayType;
1101 if (MinWidth && (arrayType = getAsArrayType(T))) {
1102 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001103 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001104 else if (isa<ConstantArrayType>(arrayType) &&
1105 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001106 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001107
John McCall33ddac02011-01-19 10:06:00 +00001108 // Walk through any array types while we're at it.
1109 T = getBaseElementType(arrayType);
1110 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001111 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001112 }
John McCall4e819612011-01-20 07:57:12 +00001113
1114 // Fields can be subject to extra alignment constraints, like if
1115 // the field is packed, the struct is packed, or the struct has a
1116 // a max-field-alignment constraint (#pragma pack). So calculate
1117 // the actual alignment of the field within the struct, and then
1118 // (as we're expected to) constrain that by the alignment of the type.
1119 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1120 // So calculate the alignment of the field.
1121 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1122
1123 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001124 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001125
1126 // Use the GCD of that and the offset within the record.
1127 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1128 if (offset > 0) {
1129 // Alignment is always a power of 2, so the GCD will be a power of 2,
1130 // which means we get to do this crazy thing instead of Euclid's.
1131 uint64_t lowBitOfOffset = offset & (~offset + 1);
1132 if (lowBitOfOffset < fieldAlign)
1133 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1134 }
1135
1136 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001137 }
Chris Lattner68061312009-01-24 21:53:27 +00001138 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001139
Ken Dyckcc56c542011-01-15 18:38:59 +00001140 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001141}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001142
John McCallf1249922012-08-21 04:10:00 +00001143// getTypeInfoDataSizeInChars - Return the size of a type, in
1144// chars. If the type is a record, its data size is returned. This is
1145// the size of the memcpy that's performed when assigning this type
1146// using a trivial copy/move assignment operator.
1147std::pair<CharUnits, CharUnits>
1148ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1149 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1150
1151 // In C++, objects can sometimes be allocated into the tail padding
1152 // of a base-class subobject. We decide whether that's possible
1153 // during class layout, so here we can just trust the layout results.
1154 if (getLangOpts().CPlusPlus) {
1155 if (const RecordType *RT = T->getAs<RecordType>()) {
1156 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1157 sizeAndAlign.first = layout.getDataSize();
1158 }
1159 }
1160
1161 return sizeAndAlign;
1162}
1163
John McCall87fe5d52010-05-20 01:18:31 +00001164std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001165ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001166 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001167 return std::make_pair(toCharUnitsFromBits(Info.first),
1168 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001169}
1170
1171std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001172ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001173 return getTypeInfoInChars(T.getTypePtr());
1174}
1175
Daniel Dunbarc6475872012-03-09 04:12:54 +00001176std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1177 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1178 if (it != MemoizedTypeInfo.end())
1179 return it->second;
1180
1181 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1182 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1183 return Info;
1184}
1185
1186/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1187/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001188///
1189/// FIXME: Pointers into different addr spaces could have different sizes and
1190/// alignment requirements: getPointerInfo should take an AddrSpace, this
1191/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001192std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001193ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001194 uint64_t Width=0;
1195 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001196 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001197#define TYPE(Class, Base)
1198#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001199#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001200#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1201#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001202 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001203
Chris Lattner355332d2007-07-13 22:27:08 +00001204 case Type::FunctionNoProto:
1205 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001206 // GCC extension: alignof(function) = 32 bits
1207 Width = 0;
1208 Align = 32;
1209 break;
1210
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001211 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001212 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001213 Width = 0;
1214 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1215 break;
1216
Steve Naroff5c131802007-08-30 01:06:46 +00001217 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001218 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001219
Chris Lattner37e05872008-03-05 18:54:05 +00001220 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001221 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001222 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1223 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001224 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001225 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001226 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001227 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001228 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001229 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001230 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001231 const VectorType *VT = cast<VectorType>(T);
1232 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1233 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001234 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001235 // If the alignment is not a power of 2, round up to the next power of 2.
1236 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001237 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001238 Align = llvm::NextPowerOf2(Align);
1239 Width = llvm::RoundUpToAlignment(Width, Align);
1240 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001241 // Adjust the alignment based on the target max.
1242 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1243 if (TargetVectorAlign && TargetVectorAlign < Align)
1244 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001245 break;
1246 }
Chris Lattner647fb222007-07-18 18:26:58 +00001247
Chris Lattner7570e9c2008-03-08 08:52:55 +00001248 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001249 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001250 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001251 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001252 // GCC extension: alignof(void) = 8 bits.
1253 Width = 0;
1254 Align = 8;
1255 break;
1256
Chris Lattner6a4f7452007-12-19 19:23:28 +00001257 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001258 Width = Target->getBoolWidth();
1259 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001260 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001261 case BuiltinType::Char_S:
1262 case BuiltinType::Char_U:
1263 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001264 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001265 Width = Target->getCharWidth();
1266 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001267 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001268 case BuiltinType::WChar_S:
1269 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001270 Width = Target->getWCharWidth();
1271 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001272 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001273 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001274 Width = Target->getChar16Width();
1275 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001276 break;
1277 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001278 Width = Target->getChar32Width();
1279 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001280 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001281 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001282 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001283 Width = Target->getShortWidth();
1284 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001285 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001286 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001287 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001288 Width = Target->getIntWidth();
1289 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001290 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001291 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001292 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001293 Width = Target->getLongWidth();
1294 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001295 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001296 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001297 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001298 Width = Target->getLongLongWidth();
1299 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001300 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001301 case BuiltinType::Int128:
1302 case BuiltinType::UInt128:
1303 Width = 128;
1304 Align = 128; // int128_t is 128-bit aligned on all targets.
1305 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001306 case BuiltinType::Half:
1307 Width = Target->getHalfWidth();
1308 Align = Target->getHalfAlign();
1309 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001310 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001311 Width = Target->getFloatWidth();
1312 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001313 break;
1314 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001315 Width = Target->getDoubleWidth();
1316 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001317 break;
1318 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001319 Width = Target->getLongDoubleWidth();
1320 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001321 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001322 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001323 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1324 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001325 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001326 case BuiltinType::ObjCId:
1327 case BuiltinType::ObjCClass:
1328 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001329 Width = Target->getPointerWidth(0);
1330 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001331 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001332 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001333 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001334 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001335 Width = Target->getPointerWidth(0);
1336 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001337 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001338 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001339 unsigned AS = getTargetAddressSpace(
1340 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001341 Width = Target->getPointerWidth(AS);
1342 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001343 break;
1344 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001345 case Type::LValueReference:
1346 case Type::RValueReference: {
1347 // alignof and sizeof should never enter this code path here, so we go
1348 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001349 unsigned AS = getTargetAddressSpace(
1350 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001351 Width = Target->getPointerWidth(AS);
1352 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001353 break;
1354 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001355 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001356 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001357 Width = Target->getPointerWidth(AS);
1358 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001359 break;
1360 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001361 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001362 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001363 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001364 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001365 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001366 Align = PtrDiffInfo.second;
1367 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001368 }
Chris Lattner647fb222007-07-18 18:26:58 +00001369 case Type::Complex: {
1370 // Complex types have the same alignment as their elements, but twice the
1371 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001372 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001373 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001374 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001375 Align = EltInfo.second;
1376 break;
1377 }
John McCall8b07ec22010-05-15 11:32:37 +00001378 case Type::ObjCObject:
1379 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001380 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001381 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001382 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001383 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001384 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001385 break;
1386 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001387 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001388 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001389 const TagType *TT = cast<TagType>(T);
1390
1391 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001392 Width = 8;
1393 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001394 break;
1395 }
Mike Stump11289f42009-09-09 15:08:12 +00001396
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001397 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001398 return getTypeInfo(ET->getDecl()->getIntegerType());
1399
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001400 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001401 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001402 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001403 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001404 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001405 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001406
Chris Lattner63d2b362009-10-22 05:17:15 +00001407 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001408 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1409 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001410
Richard Smith30482bc2011-02-20 03:19:35 +00001411 case Type::Auto: {
1412 const AutoType *A = cast<AutoType>(T);
1413 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001414 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001415 }
1416
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001417 case Type::Paren:
1418 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1419
Douglas Gregoref462e62009-04-30 17:32:17 +00001420 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001421 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001422 std::pair<uint64_t, unsigned> Info
1423 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001424 // If the typedef has an aligned attribute on it, it overrides any computed
1425 // alignment we have. This violates the GCC documentation (which says that
1426 // attribute(aligned) can only round up) but matches its implementation.
1427 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1428 Align = AttrAlign;
1429 else
1430 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001431 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001432 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001433 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001434
1435 case Type::TypeOfExpr:
1436 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1437 .getTypePtr());
1438
1439 case Type::TypeOf:
1440 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1441
Anders Carlsson81df7b82009-06-24 19:06:50 +00001442 case Type::Decltype:
1443 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1444 .getTypePtr());
1445
Alexis Hunte852b102011-05-24 22:41:36 +00001446 case Type::UnaryTransform:
1447 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1448
Abramo Bagnara6150c882010-05-11 21:36:43 +00001449 case Type::Elaborated:
1450 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001451
John McCall81904512011-01-06 01:58:22 +00001452 case Type::Attributed:
1453 return getTypeInfo(
1454 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1455
Richard Smith3f1b5d02011-05-05 21:57:07 +00001456 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001457 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001458 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001459 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1460 // A type alias template specialization may refer to a typedef with the
1461 // aligned attribute on it.
1462 if (TST->isTypeAlias())
1463 return getTypeInfo(TST->getAliasedType().getTypePtr());
1464 else
1465 return getTypeInfo(getCanonicalType(T));
1466 }
1467
Eli Friedman0dfb8892011-10-06 23:00:33 +00001468 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001469 std::pair<uint64_t, unsigned> Info
1470 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1471 Width = Info.first;
1472 Align = Info.second;
1473 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1474 llvm::isPowerOf2_64(Width)) {
1475 // We can potentially perform lock-free atomic operations for this
1476 // type; promote the alignment appropriately.
1477 // FIXME: We could potentially promote the width here as well...
1478 // is that worthwhile? (Non-struct atomic types generally have
1479 // power-of-two size anyway, but structs might not. Requires a bit
1480 // of implementation work to make sure we zero out the extra bits.)
1481 Align = static_cast<unsigned>(Width);
1482 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001483 }
1484
Douglas Gregoref462e62009-04-30 17:32:17 +00001485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001487 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001488 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001489}
1490
Ken Dyckcc56c542011-01-15 18:38:59 +00001491/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1492CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1493 return CharUnits::fromQuantity(BitSize / getCharWidth());
1494}
1495
Ken Dyckb0fcc592011-02-11 01:54:29 +00001496/// toBits - Convert a size in characters to a size in characters.
1497int64_t ASTContext::toBits(CharUnits CharSize) const {
1498 return CharSize.getQuantity() * getCharWidth();
1499}
1500
Ken Dyck8c89d592009-12-22 14:23:30 +00001501/// getTypeSizeInChars - Return the size of the specified type, in characters.
1502/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001503CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001504 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001505}
Jay Foad39c79802011-01-12 09:06:06 +00001506CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001507 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001508}
1509
Ken Dycka6046ab2010-01-26 17:25:18 +00001510/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001511/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001512CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001513 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001514}
Jay Foad39c79802011-01-12 09:06:06 +00001515CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001516 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001517}
1518
Chris Lattnera3402cd2009-01-27 18:08:34 +00001519/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1520/// type for the current target in bits. This can be different than the ABI
1521/// alignment in cases where it is beneficial for performance to overalign
1522/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001523unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001524 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001525
1526 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001527 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001528 T = CT->getElementType().getTypePtr();
1529 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001530 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1531 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001532 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1533
Chris Lattnera3402cd2009-01-27 18:08:34 +00001534 return ABIAlign;
1535}
1536
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001537/// DeepCollectObjCIvars -
1538/// This routine first collects all declared, but not synthesized, ivars in
1539/// super class and then collects all ivars, including those synthesized for
1540/// current class. This routine is used for implementation of current class
1541/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001542///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001543void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1544 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001545 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001546 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1547 DeepCollectObjCIvars(SuperClass, false, Ivars);
1548 if (!leafClass) {
1549 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1550 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001551 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001552 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001553 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001554 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001555 Iv= Iv->getNextIvar())
1556 Ivars.push_back(Iv);
1557 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001558}
1559
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001560/// CollectInheritedProtocols - Collect all protocols in current class and
1561/// those inherited by it.
1562void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001563 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001564 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001565 // We can use protocol_iterator here instead of
1566 // all_referenced_protocol_iterator since we are walking all categories.
1567 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1568 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001569 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001570 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001571 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001572 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001573 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001574 CollectInheritedProtocols(*P, Protocols);
1575 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001576 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001577
1578 // Categories of this Interface.
1579 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1580 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1581 CollectInheritedProtocols(CDeclChain, Protocols);
1582 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1583 while (SD) {
1584 CollectInheritedProtocols(SD, Protocols);
1585 SD = SD->getSuperClass();
1586 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001587 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001588 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001589 PE = OC->protocol_end(); P != PE; ++P) {
1590 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001591 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001592 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1593 PE = Proto->protocol_end(); P != PE; ++P)
1594 CollectInheritedProtocols(*P, Protocols);
1595 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001596 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001597 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1598 PE = OP->protocol_end(); P != PE; ++P) {
1599 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001600 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001601 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1602 PE = Proto->protocol_end(); P != PE; ++P)
1603 CollectInheritedProtocols(*P, Protocols);
1604 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001605 }
1606}
1607
Jay Foad39c79802011-01-12 09:06:06 +00001608unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001609 unsigned count = 0;
1610 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001611 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1612 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001613 count += CDecl->ivar_size();
1614
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001615 // Count ivar defined in this class's implementation. This
1616 // includes synthesized ivars.
1617 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001618 count += ImplDecl->ivar_size();
1619
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001620 return count;
1621}
1622
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001623bool ASTContext::isSentinelNullExpr(const Expr *E) {
1624 if (!E)
1625 return false;
1626
1627 // nullptr_t is always treated as null.
1628 if (E->getType()->isNullPtrType()) return true;
1629
1630 if (E->getType()->isAnyPointerType() &&
1631 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1632 Expr::NPC_ValueDependentIsNull))
1633 return true;
1634
1635 // Unfortunately, __null has type 'int'.
1636 if (isa<GNUNullExpr>(E)) return true;
1637
1638 return false;
1639}
1640
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001641/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1642ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1643 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1644 I = ObjCImpls.find(D);
1645 if (I != ObjCImpls.end())
1646 return cast<ObjCImplementationDecl>(I->second);
1647 return 0;
1648}
1649/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1650ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1651 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1652 I = ObjCImpls.find(D);
1653 if (I != ObjCImpls.end())
1654 return cast<ObjCCategoryImplDecl>(I->second);
1655 return 0;
1656}
1657
1658/// \brief Set the implementation of ObjCInterfaceDecl.
1659void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1660 ObjCImplementationDecl *ImplD) {
1661 assert(IFaceD && ImplD && "Passed null params");
1662 ObjCImpls[IFaceD] = ImplD;
1663}
1664/// \brief Set the implementation of ObjCCategoryDecl.
1665void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1666 ObjCCategoryImplDecl *ImplD) {
1667 assert(CatD && ImplD && "Passed null params");
1668 ObjCImpls[CatD] = ImplD;
1669}
1670
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001671ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1672 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1673 return ID;
1674 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1675 return CD->getClassInterface();
1676 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1677 return IMD->getClassInterface();
1678
1679 return 0;
1680}
1681
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001682/// \brief Get the copy initialization expression of VarDecl,or NULL if
1683/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001684Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001685 assert(VD && "Passed null params");
1686 assert(VD->hasAttr<BlocksAttr>() &&
1687 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001688 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001689 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001690 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1691}
1692
1693/// \brief Set the copy inialization expression of a block var decl.
1694void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1695 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001696 assert(VD->hasAttr<BlocksAttr>() &&
1697 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001698 BlockVarCopyInits[VD] = Init;
1699}
1700
John McCallbcd03502009-12-07 02:54:59 +00001701TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001702 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001703 if (!DataSize)
1704 DataSize = TypeLoc::getFullDataSizeForType(T);
1705 else
1706 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001707 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001708
John McCallbcd03502009-12-07 02:54:59 +00001709 TypeSourceInfo *TInfo =
1710 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1711 new (TInfo) TypeSourceInfo(T);
1712 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001713}
1714
John McCallbcd03502009-12-07 02:54:59 +00001715TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001716 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001717 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001718 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001719 return DI;
1720}
1721
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001722const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001723ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001724 return getObjCLayout(D, 0);
1725}
1726
1727const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001728ASTContext::getASTObjCImplementationLayout(
1729 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001730 return getObjCLayout(D->getClassInterface(), D);
1731}
1732
Chris Lattner983a8bb2007-07-13 22:13:22 +00001733//===----------------------------------------------------------------------===//
1734// Type creation/memoization methods
1735//===----------------------------------------------------------------------===//
1736
Jay Foad39c79802011-01-12 09:06:06 +00001737QualType
John McCall33ddac02011-01-19 10:06:00 +00001738ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1739 unsigned fastQuals = quals.getFastQualifiers();
1740 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001741
1742 // Check if we've already instantiated this type.
1743 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001744 ExtQuals::Profile(ID, baseType, quals);
1745 void *insertPos = 0;
1746 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1747 assert(eq->getQualifiers() == quals);
1748 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001749 }
1750
John McCall33ddac02011-01-19 10:06:00 +00001751 // If the base type is not canonical, make the appropriate canonical type.
1752 QualType canon;
1753 if (!baseType->isCanonicalUnqualified()) {
1754 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001755 canonSplit.Quals.addConsistentQualifiers(quals);
1756 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001757
1758 // Re-find the insert position.
1759 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1760 }
1761
1762 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1763 ExtQualNodes.InsertNode(eq, insertPos);
1764 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001765}
1766
Jay Foad39c79802011-01-12 09:06:06 +00001767QualType
1768ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001769 QualType CanT = getCanonicalType(T);
1770 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001771 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001772
John McCall8ccfcb52009-09-24 19:53:00 +00001773 // If we are composing extended qualifiers together, merge together
1774 // into one ExtQuals node.
1775 QualifierCollector Quals;
1776 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001777
John McCall8ccfcb52009-09-24 19:53:00 +00001778 // If this type already has an address space specified, it cannot get
1779 // another one.
1780 assert(!Quals.hasAddressSpace() &&
1781 "Type cannot be in multiple addr spaces!");
1782 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001783
John McCall8ccfcb52009-09-24 19:53:00 +00001784 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001785}
1786
Chris Lattnerd60183d2009-02-18 22:53:11 +00001787QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001788 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001789 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001790 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001791 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001792
John McCall53fa7142010-12-24 02:08:15 +00001793 if (const PointerType *ptr = T->getAs<PointerType>()) {
1794 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001795 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001796 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1797 return getPointerType(ResultType);
1798 }
1799 }
Mike Stump11289f42009-09-09 15:08:12 +00001800
John McCall8ccfcb52009-09-24 19:53:00 +00001801 // If we are composing extended qualifiers together, merge together
1802 // into one ExtQuals node.
1803 QualifierCollector Quals;
1804 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001805
John McCall8ccfcb52009-09-24 19:53:00 +00001806 // If this type already has an ObjCGC specified, it cannot get
1807 // another one.
1808 assert(!Quals.hasObjCGCAttr() &&
1809 "Type cannot have multiple ObjCGCs!");
1810 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001811
John McCall8ccfcb52009-09-24 19:53:00 +00001812 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001813}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001814
John McCall4f5019e2010-12-19 02:44:49 +00001815const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1816 FunctionType::ExtInfo Info) {
1817 if (T->getExtInfo() == Info)
1818 return T;
1819
1820 QualType Result;
1821 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1822 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1823 } else {
1824 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1825 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1826 EPI.ExtInfo = Info;
1827 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1828 FPT->getNumArgs(), EPI);
1829 }
1830
1831 return cast<FunctionType>(Result.getTypePtr());
1832}
1833
Chris Lattnerc6395932007-06-22 20:56:16 +00001834/// getComplexType - Return the uniqued reference to the type for a complex
1835/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001836QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001837 // Unique pointers, to guarantee there is only one pointer of a particular
1838 // structure.
1839 llvm::FoldingSetNodeID ID;
1840 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001841
Chris Lattnerc6395932007-06-22 20:56:16 +00001842 void *InsertPos = 0;
1843 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1844 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattnerc6395932007-06-22 20:56:16 +00001846 // If the pointee type isn't canonical, this won't be a canonical type either,
1847 // so fill in the canonical type field.
1848 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001849 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001850 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001851
Chris Lattnerc6395932007-06-22 20:56:16 +00001852 // Get the new insert position for the node we care about.
1853 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001854 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001855 }
John McCall90d1c2d2009-09-24 23:30:46 +00001856 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001857 Types.push_back(New);
1858 ComplexTypes.InsertNode(New, InsertPos);
1859 return QualType(New, 0);
1860}
1861
Chris Lattner970e54e2006-11-12 00:37:36 +00001862/// getPointerType - Return the uniqued reference to the type for a pointer to
1863/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001864QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001865 // Unique pointers, to guarantee there is only one pointer of a particular
1866 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001867 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001868 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001869
Chris Lattner67521df2007-01-27 01:29:36 +00001870 void *InsertPos = 0;
1871 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001872 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001873
Chris Lattner7ccecb92006-11-12 08:50:50 +00001874 // If the pointee type isn't canonical, this won't be a canonical type either,
1875 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001876 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001877 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001878 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001879
Chris Lattner67521df2007-01-27 01:29:36 +00001880 // Get the new insert position for the node we care about.
1881 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001882 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001883 }
John McCall90d1c2d2009-09-24 23:30:46 +00001884 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001885 Types.push_back(New);
1886 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001887 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001888}
1889
Mike Stump11289f42009-09-09 15:08:12 +00001890/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001891/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001892QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001893 assert(T->isFunctionType() && "block of function types only");
1894 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001895 // structure.
1896 llvm::FoldingSetNodeID ID;
1897 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001898
Steve Naroffec33ed92008-08-27 16:04:49 +00001899 void *InsertPos = 0;
1900 if (BlockPointerType *PT =
1901 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1902 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001903
1904 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001905 // type either so fill in the canonical type field.
1906 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001907 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001908 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001909
Steve Naroffec33ed92008-08-27 16:04:49 +00001910 // Get the new insert position for the node we care about.
1911 BlockPointerType *NewIP =
1912 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001913 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001914 }
John McCall90d1c2d2009-09-24 23:30:46 +00001915 BlockPointerType *New
1916 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001917 Types.push_back(New);
1918 BlockPointerTypes.InsertNode(New, InsertPos);
1919 return QualType(New, 0);
1920}
1921
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001922/// getLValueReferenceType - Return the uniqued reference to the type for an
1923/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001924QualType
1925ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001926 assert(getCanonicalType(T) != OverloadTy &&
1927 "Unresolved overloaded function type");
1928
Bill Wendling3708c182007-05-27 10:15:43 +00001929 // Unique pointers, to guarantee there is only one pointer of a particular
1930 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001931 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001932 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001933
1934 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001935 if (LValueReferenceType *RT =
1936 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001937 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001938
John McCallfc93cf92009-10-22 22:37:11 +00001939 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1940
Bill Wendling3708c182007-05-27 10:15:43 +00001941 // If the referencee type isn't canonical, this won't be a canonical type
1942 // either, so fill in the canonical type field.
1943 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001944 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1945 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1946 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001947
Bill Wendling3708c182007-05-27 10:15:43 +00001948 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001949 LValueReferenceType *NewIP =
1950 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001951 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001952 }
1953
John McCall90d1c2d2009-09-24 23:30:46 +00001954 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001955 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1956 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001957 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001958 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001959
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001960 return QualType(New, 0);
1961}
1962
1963/// getRValueReferenceType - Return the uniqued reference to the type for an
1964/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001965QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001966 // Unique pointers, to guarantee there is only one pointer of a particular
1967 // structure.
1968 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001969 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001970
1971 void *InsertPos = 0;
1972 if (RValueReferenceType *RT =
1973 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1974 return QualType(RT, 0);
1975
John McCallfc93cf92009-10-22 22:37:11 +00001976 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1977
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001978 // If the referencee type isn't canonical, this won't be a canonical type
1979 // either, so fill in the canonical type field.
1980 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001981 if (InnerRef || !T.isCanonical()) {
1982 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1983 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001984
1985 // Get the new insert position for the node we care about.
1986 RValueReferenceType *NewIP =
1987 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001988 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001989 }
1990
John McCall90d1c2d2009-09-24 23:30:46 +00001991 RValueReferenceType *New
1992 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001993 Types.push_back(New);
1994 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001995 return QualType(New, 0);
1996}
1997
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001998/// getMemberPointerType - Return the uniqued reference to the type for a
1999/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002000QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002001 // Unique pointers, to guarantee there is only one pointer of a particular
2002 // structure.
2003 llvm::FoldingSetNodeID ID;
2004 MemberPointerType::Profile(ID, T, Cls);
2005
2006 void *InsertPos = 0;
2007 if (MemberPointerType *PT =
2008 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2009 return QualType(PT, 0);
2010
2011 // If the pointee or class type isn't canonical, this won't be a canonical
2012 // type either, so fill in the canonical type field.
2013 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002014 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002015 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2016
2017 // Get the new insert position for the node we care about.
2018 MemberPointerType *NewIP =
2019 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002020 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002021 }
John McCall90d1c2d2009-09-24 23:30:46 +00002022 MemberPointerType *New
2023 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002024 Types.push_back(New);
2025 MemberPointerTypes.InsertNode(New, InsertPos);
2026 return QualType(New, 0);
2027}
2028
Mike Stump11289f42009-09-09 15:08:12 +00002029/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002030/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002031QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002032 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002033 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002034 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002035 assert((EltTy->isDependentType() ||
2036 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002037 "Constant array of VLAs is illegal!");
2038
Chris Lattnere2df3f92009-05-13 04:12:56 +00002039 // Convert the array size into a canonical width matching the pointer size for
2040 // the target.
2041 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002042 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002043 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002044
Chris Lattner23b7eb62007-06-15 23:05:46 +00002045 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002046 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002047
Chris Lattner36f8e652007-01-27 08:31:04 +00002048 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002049 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002050 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002051 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002052
John McCall33ddac02011-01-19 10:06:00 +00002053 // If the element type isn't canonical or has qualifiers, this won't
2054 // be a canonical type either, so fill in the canonical type field.
2055 QualType Canon;
2056 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2057 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002058 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002059 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002060 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002061
Chris Lattner36f8e652007-01-27 08:31:04 +00002062 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002063 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002064 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002065 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067
John McCall90d1c2d2009-09-24 23:30:46 +00002068 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002069 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002070 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002071 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002072 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002073}
2074
John McCall06549462011-01-18 08:40:38 +00002075/// getVariableArrayDecayedType - Turns the given type, which may be
2076/// variably-modified, into the corresponding type with all the known
2077/// sizes replaced with [*].
2078QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2079 // Vastly most common case.
2080 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002081
John McCall06549462011-01-18 08:40:38 +00002082 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002083
John McCall06549462011-01-18 08:40:38 +00002084 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002085 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002086 switch (ty->getTypeClass()) {
2087#define TYPE(Class, Base)
2088#define ABSTRACT_TYPE(Class, Base)
2089#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2090#include "clang/AST/TypeNodes.def"
2091 llvm_unreachable("didn't desugar past all non-canonical types?");
2092
2093 // These types should never be variably-modified.
2094 case Type::Builtin:
2095 case Type::Complex:
2096 case Type::Vector:
2097 case Type::ExtVector:
2098 case Type::DependentSizedExtVector:
2099 case Type::ObjCObject:
2100 case Type::ObjCInterface:
2101 case Type::ObjCObjectPointer:
2102 case Type::Record:
2103 case Type::Enum:
2104 case Type::UnresolvedUsing:
2105 case Type::TypeOfExpr:
2106 case Type::TypeOf:
2107 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002108 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002109 case Type::DependentName:
2110 case Type::InjectedClassName:
2111 case Type::TemplateSpecialization:
2112 case Type::DependentTemplateSpecialization:
2113 case Type::TemplateTypeParm:
2114 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002115 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002116 case Type::PackExpansion:
2117 llvm_unreachable("type should never be variably-modified");
2118
2119 // These types can be variably-modified but should never need to
2120 // further decay.
2121 case Type::FunctionNoProto:
2122 case Type::FunctionProto:
2123 case Type::BlockPointer:
2124 case Type::MemberPointer:
2125 return type;
2126
2127 // These types can be variably-modified. All these modifications
2128 // preserve structure except as noted by comments.
2129 // TODO: if we ever care about optimizing VLAs, there are no-op
2130 // optimizations available here.
2131 case Type::Pointer:
2132 result = getPointerType(getVariableArrayDecayedType(
2133 cast<PointerType>(ty)->getPointeeType()));
2134 break;
2135
2136 case Type::LValueReference: {
2137 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2138 result = getLValueReferenceType(
2139 getVariableArrayDecayedType(lv->getPointeeType()),
2140 lv->isSpelledAsLValue());
2141 break;
2142 }
2143
2144 case Type::RValueReference: {
2145 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2146 result = getRValueReferenceType(
2147 getVariableArrayDecayedType(lv->getPointeeType()));
2148 break;
2149 }
2150
Eli Friedman0dfb8892011-10-06 23:00:33 +00002151 case Type::Atomic: {
2152 const AtomicType *at = cast<AtomicType>(ty);
2153 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2154 break;
2155 }
2156
John McCall06549462011-01-18 08:40:38 +00002157 case Type::ConstantArray: {
2158 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2159 result = getConstantArrayType(
2160 getVariableArrayDecayedType(cat->getElementType()),
2161 cat->getSize(),
2162 cat->getSizeModifier(),
2163 cat->getIndexTypeCVRQualifiers());
2164 break;
2165 }
2166
2167 case Type::DependentSizedArray: {
2168 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2169 result = getDependentSizedArrayType(
2170 getVariableArrayDecayedType(dat->getElementType()),
2171 dat->getSizeExpr(),
2172 dat->getSizeModifier(),
2173 dat->getIndexTypeCVRQualifiers(),
2174 dat->getBracketsRange());
2175 break;
2176 }
2177
2178 // Turn incomplete types into [*] types.
2179 case Type::IncompleteArray: {
2180 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2181 result = getVariableArrayType(
2182 getVariableArrayDecayedType(iat->getElementType()),
2183 /*size*/ 0,
2184 ArrayType::Normal,
2185 iat->getIndexTypeCVRQualifiers(),
2186 SourceRange());
2187 break;
2188 }
2189
2190 // Turn VLA types into [*] types.
2191 case Type::VariableArray: {
2192 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2193 result = getVariableArrayType(
2194 getVariableArrayDecayedType(vat->getElementType()),
2195 /*size*/ 0,
2196 ArrayType::Star,
2197 vat->getIndexTypeCVRQualifiers(),
2198 vat->getBracketsRange());
2199 break;
2200 }
2201 }
2202
2203 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002204 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002205}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002206
Steve Naroffcadebd02007-08-30 18:14:25 +00002207/// getVariableArrayType - Returns a non-unique reference to the type for a
2208/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002209QualType ASTContext::getVariableArrayType(QualType EltTy,
2210 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002211 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002212 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002213 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002214 // Since we don't unique expressions, it isn't possible to unique VLA's
2215 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002216 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002217
John McCall33ddac02011-01-19 10:06:00 +00002218 // Be sure to pull qualifiers off the element type.
2219 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2220 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002221 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002222 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002223 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002224 }
2225
John McCall90d1c2d2009-09-24 23:30:46 +00002226 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002227 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002228
2229 VariableArrayTypes.push_back(New);
2230 Types.push_back(New);
2231 return QualType(New, 0);
2232}
2233
Douglas Gregor4619e432008-12-05 23:32:09 +00002234/// getDependentSizedArrayType - Returns a non-unique reference to
2235/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002236/// type.
John McCall33ddac02011-01-19 10:06:00 +00002237QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2238 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002239 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002240 unsigned elementTypeQuals,
2241 SourceRange brackets) const {
2242 assert((!numElements || numElements->isTypeDependent() ||
2243 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002244 "Size must be type- or value-dependent!");
2245
John McCall33ddac02011-01-19 10:06:00 +00002246 // Dependently-sized array types that do not have a specified number
2247 // of elements will have their sizes deduced from a dependent
2248 // initializer. We do no canonicalization here at all, which is okay
2249 // because they can't be used in most locations.
2250 if (!numElements) {
2251 DependentSizedArrayType *newType
2252 = new (*this, TypeAlignment)
2253 DependentSizedArrayType(*this, elementType, QualType(),
2254 numElements, ASM, elementTypeQuals,
2255 brackets);
2256 Types.push_back(newType);
2257 return QualType(newType, 0);
2258 }
2259
2260 // Otherwise, we actually build a new type every time, but we
2261 // also build a canonical type.
2262
2263 SplitQualType canonElementType = getCanonicalType(elementType).split();
2264
2265 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002266 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002267 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002268 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002269 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002270
John McCall33ddac02011-01-19 10:06:00 +00002271 // Look for an existing type with these properties.
2272 DependentSizedArrayType *canonTy =
2273 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002274
John McCall33ddac02011-01-19 10:06:00 +00002275 // If we don't have one, build one.
2276 if (!canonTy) {
2277 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002278 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002279 QualType(), numElements, ASM, elementTypeQuals,
2280 brackets);
2281 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2282 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002283 }
2284
John McCall33ddac02011-01-19 10:06:00 +00002285 // Apply qualifiers from the element type to the array.
2286 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002287 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002288
John McCall33ddac02011-01-19 10:06:00 +00002289 // If we didn't need extra canonicalization for the element type,
2290 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002291 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002292 return canon;
2293
2294 // Otherwise, we need to build a type which follows the spelling
2295 // of the element type.
2296 DependentSizedArrayType *sugaredType
2297 = new (*this, TypeAlignment)
2298 DependentSizedArrayType(*this, elementType, canon, numElements,
2299 ASM, elementTypeQuals, brackets);
2300 Types.push_back(sugaredType);
2301 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002302}
2303
John McCall33ddac02011-01-19 10:06:00 +00002304QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002305 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002306 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002307 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002308 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002309
John McCall33ddac02011-01-19 10:06:00 +00002310 void *insertPos = 0;
2311 if (IncompleteArrayType *iat =
2312 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2313 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002314
2315 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002316 // either, so fill in the canonical type field. We also have to pull
2317 // qualifiers off the element type.
2318 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002319
John McCall33ddac02011-01-19 10:06:00 +00002320 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2321 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002322 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002323 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002324 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002325
2326 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002327 IncompleteArrayType *existing =
2328 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2329 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002330 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002331
John McCall33ddac02011-01-19 10:06:00 +00002332 IncompleteArrayType *newType = new (*this, TypeAlignment)
2333 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002334
John McCall33ddac02011-01-19 10:06:00 +00002335 IncompleteArrayTypes.InsertNode(newType, insertPos);
2336 Types.push_back(newType);
2337 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002338}
2339
Steve Naroff91fcddb2007-07-18 18:00:27 +00002340/// getVectorType - Return the unique reference to a vector type of
2341/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002342QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002343 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002344 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002345
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002346 // Check if we've already instantiated a vector of this type.
2347 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002348 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002349
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002350 void *InsertPos = 0;
2351 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2352 return QualType(VTP, 0);
2353
2354 // If the element type isn't canonical, this won't be a canonical type either,
2355 // so fill in the canonical type field.
2356 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002357 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002358 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002359
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002360 // Get the new insert position for the node we care about.
2361 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002362 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002363 }
John McCall90d1c2d2009-09-24 23:30:46 +00002364 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002365 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002366 VectorTypes.InsertNode(New, InsertPos);
2367 Types.push_back(New);
2368 return QualType(New, 0);
2369}
2370
Nate Begemance4d7fc2008-04-18 23:10:10 +00002371/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002372/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002373QualType
2374ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002375 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002376
Steve Naroff91fcddb2007-07-18 18:00:27 +00002377 // Check if we've already instantiated a vector of this type.
2378 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002379 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002380 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002381 void *InsertPos = 0;
2382 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2383 return QualType(VTP, 0);
2384
2385 // If the element type isn't canonical, this won't be a canonical type either,
2386 // so fill in the canonical type field.
2387 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002388 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002389 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002390
Steve Naroff91fcddb2007-07-18 18:00:27 +00002391 // Get the new insert position for the node we care about.
2392 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002393 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002394 }
John McCall90d1c2d2009-09-24 23:30:46 +00002395 ExtVectorType *New = new (*this, TypeAlignment)
2396 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002397 VectorTypes.InsertNode(New, InsertPos);
2398 Types.push_back(New);
2399 return QualType(New, 0);
2400}
2401
Jay Foad39c79802011-01-12 09:06:06 +00002402QualType
2403ASTContext::getDependentSizedExtVectorType(QualType vecType,
2404 Expr *SizeExpr,
2405 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002406 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002407 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002408 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002409
Douglas Gregor352169a2009-07-31 03:54:25 +00002410 void *InsertPos = 0;
2411 DependentSizedExtVectorType *Canon
2412 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2413 DependentSizedExtVectorType *New;
2414 if (Canon) {
2415 // We already have a canonical version of this array type; use it as
2416 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002417 New = new (*this, TypeAlignment)
2418 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2419 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002420 } else {
2421 QualType CanonVecTy = getCanonicalType(vecType);
2422 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002423 New = new (*this, TypeAlignment)
2424 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2425 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002426
2427 DependentSizedExtVectorType *CanonCheck
2428 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2429 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2430 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002431 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2432 } else {
2433 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2434 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002435 New = new (*this, TypeAlignment)
2436 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002437 }
2438 }
Mike Stump11289f42009-09-09 15:08:12 +00002439
Douglas Gregor758a8692009-06-17 21:51:59 +00002440 Types.push_back(New);
2441 return QualType(New, 0);
2442}
2443
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002444/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002445///
Jay Foad39c79802011-01-12 09:06:06 +00002446QualType
2447ASTContext::getFunctionNoProtoType(QualType ResultTy,
2448 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002449 const CallingConv DefaultCC = Info.getCC();
2450 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2451 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002452 // Unique functions, to guarantee there is only one function of a particular
2453 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002454 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002455 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002456
Chris Lattner47955de2007-01-27 08:37:20 +00002457 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002458 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002459 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002460 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002461
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002462 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002463 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002464 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002465 Canonical =
2466 getFunctionNoProtoType(getCanonicalType(ResultTy),
2467 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002468
Chris Lattner47955de2007-01-27 08:37:20 +00002469 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002470 FunctionNoProtoType *NewIP =
2471 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002472 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002473 }
Mike Stump11289f42009-09-09 15:08:12 +00002474
Roman Divacky65b88cd2011-03-01 17:40:53 +00002475 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002476 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002477 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002478 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002479 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002480 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002481}
2482
2483/// getFunctionType - Return a normal function type with a typed argument
2484/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002485QualType
2486ASTContext::getFunctionType(QualType ResultTy,
2487 const QualType *ArgArray, unsigned NumArgs,
2488 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002489 // Unique functions, to guarantee there is only one function of a particular
2490 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002491 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002492 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002493
2494 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002495 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002496 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002497 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002498
2499 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002500 bool isCanonical =
2501 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2502 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002503 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002504 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002505 isCanonical = false;
2506
Roman Divacky65b88cd2011-03-01 17:40:53 +00002507 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2508 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2509 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002510
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002511 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002512 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002513 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002514 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002515 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002516 CanonicalArgs.reserve(NumArgs);
2517 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002518 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002519
John McCalldb40c7f2010-12-14 08:05:40 +00002520 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002521 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002522 CanonicalEPI.ExceptionSpecType = EST_None;
2523 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002524 CanonicalEPI.ExtInfo
2525 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2526
Chris Lattner76a00cf2008-04-06 22:59:24 +00002527 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002528 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002529 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002530
Chris Lattnerfd4de792007-01-27 01:15:32 +00002531 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002532 FunctionProtoType *NewIP =
2533 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002534 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002535 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002536
John McCall31168b02011-06-15 23:02:42 +00002537 // FunctionProtoType objects are allocated with extra bytes after
2538 // them for three variable size arrays at the end:
2539 // - parameter types
2540 // - exception types
2541 // - consumed-arguments flags
2542 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002543 // expression, or information used to resolve the exception
2544 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002545 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002546 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002547 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002548 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002549 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002550 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002551 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002552 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002553 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2554 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002555 }
John McCall31168b02011-06-15 23:02:42 +00002556 if (EPI.ConsumedArguments)
2557 Size += NumArgs * sizeof(bool);
2558
John McCalldb40c7f2010-12-14 08:05:40 +00002559 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002560 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2561 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002562 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002563 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002564 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002565 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002566}
Chris Lattneref51c202006-11-10 07:17:23 +00002567
John McCalle78aac42010-03-10 03:28:59 +00002568#ifndef NDEBUG
2569static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2570 if (!isa<CXXRecordDecl>(D)) return false;
2571 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2572 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2573 return true;
2574 if (RD->getDescribedClassTemplate() &&
2575 !isa<ClassTemplateSpecializationDecl>(RD))
2576 return true;
2577 return false;
2578}
2579#endif
2580
2581/// getInjectedClassNameType - Return the unique reference to the
2582/// injected class name type for the specified templated declaration.
2583QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002584 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002585 assert(NeedsInjectedClassNameType(Decl));
2586 if (Decl->TypeForDecl) {
2587 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002588 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002589 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2590 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2591 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2592 } else {
John McCall424cec92011-01-19 06:33:43 +00002593 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002594 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002595 Decl->TypeForDecl = newType;
2596 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002597 }
2598 return QualType(Decl->TypeForDecl, 0);
2599}
2600
Douglas Gregor83a586e2008-04-13 21:07:44 +00002601/// getTypeDeclType - Return the unique reference to the type for the
2602/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002603QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002604 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002605 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002606
Richard Smithdda56e42011-04-15 14:24:37 +00002607 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002608 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002609
John McCall96f0b5f2010-03-10 06:48:02 +00002610 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2611 "Template type parameter types are always available.");
2612
John McCall81e38502010-02-16 03:57:14 +00002613 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002614 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002615 "struct/union has previous declaration");
2616 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002617 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002618 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002619 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002620 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002621 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002622 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002623 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002624 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2625 Decl->TypeForDecl = newType;
2626 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002627 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002628 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002629
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002630 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002631}
2632
Chris Lattner32d920b2007-01-26 02:01:53 +00002633/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002634/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002635QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002636ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2637 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002638 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002639
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002640 if (Canonical.isNull())
2641 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002642 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002643 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002644 Decl->TypeForDecl = newType;
2645 Types.push_back(newType);
2646 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002647}
2648
Jay Foad39c79802011-01-12 09:06:06 +00002649QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002650 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2651
Douglas Gregorec9fd132012-01-14 16:38:05 +00002652 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002653 if (PrevDecl->TypeForDecl)
2654 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2655
John McCall424cec92011-01-19 06:33:43 +00002656 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2657 Decl->TypeForDecl = newType;
2658 Types.push_back(newType);
2659 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002660}
2661
Jay Foad39c79802011-01-12 09:06:06 +00002662QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002663 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2664
Douglas Gregorec9fd132012-01-14 16:38:05 +00002665 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002666 if (PrevDecl->TypeForDecl)
2667 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2668
John McCall424cec92011-01-19 06:33:43 +00002669 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2670 Decl->TypeForDecl = newType;
2671 Types.push_back(newType);
2672 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002673}
2674
John McCall81904512011-01-06 01:58:22 +00002675QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2676 QualType modifiedType,
2677 QualType equivalentType) {
2678 llvm::FoldingSetNodeID id;
2679 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2680
2681 void *insertPos = 0;
2682 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2683 if (type) return QualType(type, 0);
2684
2685 QualType canon = getCanonicalType(equivalentType);
2686 type = new (*this, TypeAlignment)
2687 AttributedType(canon, attrKind, modifiedType, equivalentType);
2688
2689 Types.push_back(type);
2690 AttributedTypes.InsertNode(type, insertPos);
2691
2692 return QualType(type, 0);
2693}
2694
2695
John McCallcebee162009-10-18 09:09:24 +00002696/// \brief Retrieve a substitution-result type.
2697QualType
2698ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002699 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002700 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002701 && "replacement types must always be canonical");
2702
2703 llvm::FoldingSetNodeID ID;
2704 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2705 void *InsertPos = 0;
2706 SubstTemplateTypeParmType *SubstParm
2707 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2708
2709 if (!SubstParm) {
2710 SubstParm = new (*this, TypeAlignment)
2711 SubstTemplateTypeParmType(Parm, Replacement);
2712 Types.push_back(SubstParm);
2713 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2714 }
2715
2716 return QualType(SubstParm, 0);
2717}
2718
Douglas Gregorada4b792011-01-14 02:55:32 +00002719/// \brief Retrieve a
2720QualType ASTContext::getSubstTemplateTypeParmPackType(
2721 const TemplateTypeParmType *Parm,
2722 const TemplateArgument &ArgPack) {
2723#ifndef NDEBUG
2724 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2725 PEnd = ArgPack.pack_end();
2726 P != PEnd; ++P) {
2727 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2728 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2729 }
2730#endif
2731
2732 llvm::FoldingSetNodeID ID;
2733 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2734 void *InsertPos = 0;
2735 if (SubstTemplateTypeParmPackType *SubstParm
2736 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2737 return QualType(SubstParm, 0);
2738
2739 QualType Canon;
2740 if (!Parm->isCanonicalUnqualified()) {
2741 Canon = getCanonicalType(QualType(Parm, 0));
2742 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2743 ArgPack);
2744 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2745 }
2746
2747 SubstTemplateTypeParmPackType *SubstParm
2748 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2749 ArgPack);
2750 Types.push_back(SubstParm);
2751 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2752 return QualType(SubstParm, 0);
2753}
2754
Douglas Gregoreff93e02009-02-05 23:33:38 +00002755/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002756/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002757/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002758QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002759 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002760 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002761 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002762 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002763 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002764 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002765 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2766
2767 if (TypeParm)
2768 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002769
Chandler Carruth08836322011-05-01 00:51:33 +00002770 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002771 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002772 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002773
2774 TemplateTypeParmType *TypeCheck
2775 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2776 assert(!TypeCheck && "Template type parameter canonical type broken");
2777 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002778 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002779 TypeParm = new (*this, TypeAlignment)
2780 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002781
2782 Types.push_back(TypeParm);
2783 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2784
2785 return QualType(TypeParm, 0);
2786}
2787
John McCalle78aac42010-03-10 03:28:59 +00002788TypeSourceInfo *
2789ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2790 SourceLocation NameLoc,
2791 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002792 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002793 assert(!Name.getAsDependentTemplateName() &&
2794 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002795 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002796
2797 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2798 TemplateSpecializationTypeLoc TL
2799 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002800 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002801 TL.setTemplateNameLoc(NameLoc);
2802 TL.setLAngleLoc(Args.getLAngleLoc());
2803 TL.setRAngleLoc(Args.getRAngleLoc());
2804 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2805 TL.setArgLocInfo(i, Args[i].getLocInfo());
2806 return DI;
2807}
2808
Mike Stump11289f42009-09-09 15:08:12 +00002809QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002810ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002811 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002812 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002813 assert(!Template.getAsDependentTemplateName() &&
2814 "No dependent template names here!");
2815
John McCall6b51f282009-11-23 01:53:49 +00002816 unsigned NumArgs = Args.size();
2817
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002818 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002819 ArgVec.reserve(NumArgs);
2820 for (unsigned i = 0; i != NumArgs; ++i)
2821 ArgVec.push_back(Args[i].getArgument());
2822
John McCall2408e322010-04-27 00:57:59 +00002823 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002824 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002825}
2826
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002827#ifndef NDEBUG
2828static bool hasAnyPackExpansions(const TemplateArgument *Args,
2829 unsigned NumArgs) {
2830 for (unsigned I = 0; I != NumArgs; ++I)
2831 if (Args[I].isPackExpansion())
2832 return true;
2833
2834 return true;
2835}
2836#endif
2837
John McCall0ad16662009-10-29 08:12:44 +00002838QualType
2839ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002840 const TemplateArgument *Args,
2841 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002842 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002843 assert(!Template.getAsDependentTemplateName() &&
2844 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002845 // Look through qualified template names.
2846 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2847 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002848
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002849 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002850 Template.getAsTemplateDecl() &&
2851 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002852 QualType CanonType;
2853 if (!Underlying.isNull())
2854 CanonType = getCanonicalType(Underlying);
2855 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002856 // We can get here with an alias template when the specialization contains
2857 // a pack expansion that does not match up with a parameter pack.
2858 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2859 "Caller must compute aliased type");
2860 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002861 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2862 NumArgs);
2863 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002864
Douglas Gregora8e02e72009-07-28 23:00:59 +00002865 // Allocate the (non-canonical) template specialization type, but don't
2866 // try to unique it: these types typically have location information that
2867 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002868 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2869 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002870 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002871 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002872 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002873 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2874 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002875
Douglas Gregor8bf42052009-02-09 18:46:07 +00002876 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002877 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002878}
2879
Mike Stump11289f42009-09-09 15:08:12 +00002880QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002881ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2882 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002883 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002884 assert(!Template.getAsDependentTemplateName() &&
2885 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002886
Douglas Gregore29139c2011-03-03 17:04:51 +00002887 // Look through qualified template names.
2888 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2889 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002890
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002891 // Build the canonical template specialization type.
2892 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002893 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002894 CanonArgs.reserve(NumArgs);
2895 for (unsigned I = 0; I != NumArgs; ++I)
2896 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2897
2898 // Determine whether this canonical template specialization type already
2899 // exists.
2900 llvm::FoldingSetNodeID ID;
2901 TemplateSpecializationType::Profile(ID, CanonTemplate,
2902 CanonArgs.data(), NumArgs, *this);
2903
2904 void *InsertPos = 0;
2905 TemplateSpecializationType *Spec
2906 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2907
2908 if (!Spec) {
2909 // Allocate a new canonical template specialization type.
2910 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2911 sizeof(TemplateArgument) * NumArgs),
2912 TypeAlignment);
2913 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2914 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002915 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002916 Types.push_back(Spec);
2917 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2918 }
2919
2920 assert(Spec->isDependentType() &&
2921 "Non-dependent template-id type must have a canonical type");
2922 return QualType(Spec, 0);
2923}
2924
2925QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002926ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2927 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002928 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002929 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002930 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002931
2932 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002933 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002934 if (T)
2935 return QualType(T, 0);
2936
Douglas Gregorc42075a2010-02-04 18:10:26 +00002937 QualType Canon = NamedType;
2938 if (!Canon.isCanonical()) {
2939 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002940 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2941 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002942 (void)CheckT;
2943 }
2944
Abramo Bagnara6150c882010-05-11 21:36:43 +00002945 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002946 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002947 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002948 return QualType(T, 0);
2949}
2950
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002951QualType
Jay Foad39c79802011-01-12 09:06:06 +00002952ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002953 llvm::FoldingSetNodeID ID;
2954 ParenType::Profile(ID, InnerType);
2955
2956 void *InsertPos = 0;
2957 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2958 if (T)
2959 return QualType(T, 0);
2960
2961 QualType Canon = InnerType;
2962 if (!Canon.isCanonical()) {
2963 Canon = getCanonicalType(InnerType);
2964 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2965 assert(!CheckT && "Paren canonical type broken");
2966 (void)CheckT;
2967 }
2968
2969 T = new (*this) ParenType(InnerType, Canon);
2970 Types.push_back(T);
2971 ParenTypes.InsertNode(T, InsertPos);
2972 return QualType(T, 0);
2973}
2974
Douglas Gregor02085352010-03-31 20:19:30 +00002975QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2976 NestedNameSpecifier *NNS,
2977 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002978 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002979 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2980
2981 if (Canon.isNull()) {
2982 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002983 ElaboratedTypeKeyword CanonKeyword = Keyword;
2984 if (Keyword == ETK_None)
2985 CanonKeyword = ETK_Typename;
2986
2987 if (CanonNNS != NNS || CanonKeyword != Keyword)
2988 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002989 }
2990
2991 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002992 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002993
2994 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002995 DependentNameType *T
2996 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002997 if (T)
2998 return QualType(T, 0);
2999
Douglas Gregor02085352010-03-31 20:19:30 +00003000 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003001 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003002 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003003 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003004}
3005
Mike Stump11289f42009-09-09 15:08:12 +00003006QualType
John McCallc392f372010-06-11 00:33:02 +00003007ASTContext::getDependentTemplateSpecializationType(
3008 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003009 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003010 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003011 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003012 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003013 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003014 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3015 ArgCopy.push_back(Args[I].getArgument());
3016 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3017 ArgCopy.size(),
3018 ArgCopy.data());
3019}
3020
3021QualType
3022ASTContext::getDependentTemplateSpecializationType(
3023 ElaboratedTypeKeyword Keyword,
3024 NestedNameSpecifier *NNS,
3025 const IdentifierInfo *Name,
3026 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003027 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003028 assert((!NNS || NNS->isDependent()) &&
3029 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003030
Douglas Gregorc42075a2010-02-04 18:10:26 +00003031 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003032 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3033 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003034
3035 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003036 DependentTemplateSpecializationType *T
3037 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003038 if (T)
3039 return QualType(T, 0);
3040
John McCallc392f372010-06-11 00:33:02 +00003041 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003042
John McCallc392f372010-06-11 00:33:02 +00003043 ElaboratedTypeKeyword CanonKeyword = Keyword;
3044 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3045
3046 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003047 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003048 for (unsigned I = 0; I != NumArgs; ++I) {
3049 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3050 if (!CanonArgs[I].structurallyEquals(Args[I]))
3051 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003052 }
3053
John McCallc392f372010-06-11 00:33:02 +00003054 QualType Canon;
3055 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3056 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3057 Name, NumArgs,
3058 CanonArgs.data());
3059
3060 // Find the insert position again.
3061 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3062 }
3063
3064 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3065 sizeof(TemplateArgument) * NumArgs),
3066 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003067 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003068 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003069 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003070 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003071 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003072}
3073
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003074QualType ASTContext::getPackExpansionType(QualType Pattern,
3075 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003076 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003077 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003078
3079 assert(Pattern->containsUnexpandedParameterPack() &&
3080 "Pack expansions must expand one or more parameter packs");
3081 void *InsertPos = 0;
3082 PackExpansionType *T
3083 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3084 if (T)
3085 return QualType(T, 0);
3086
3087 QualType Canon;
3088 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003089 Canon = getCanonicalType(Pattern);
3090 // The canonical type might not contain an unexpanded parameter pack, if it
3091 // contains an alias template specialization which ignores one of its
3092 // parameters.
3093 if (Canon->containsUnexpandedParameterPack()) {
3094 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003095
Richard Smith68eea502012-07-16 00:20:35 +00003096 // Find the insert position again, in case we inserted an element into
3097 // PackExpansionTypes and invalidated our insert position.
3098 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3099 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003100 }
3101
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003102 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003103 Types.push_back(T);
3104 PackExpansionTypes.InsertNode(T, InsertPos);
3105 return QualType(T, 0);
3106}
3107
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003108/// CmpProtocolNames - Comparison predicate for sorting protocols
3109/// alphabetically.
3110static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3111 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003112 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003113}
3114
John McCall8b07ec22010-05-15 11:32:37 +00003115static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003116 unsigned NumProtocols) {
3117 if (NumProtocols == 0) return true;
3118
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003119 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3120 return false;
3121
John McCallfc93cf92009-10-22 22:37:11 +00003122 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003123 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3124 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003125 return false;
3126 return true;
3127}
3128
3129static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003130 unsigned &NumProtocols) {
3131 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003132
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003133 // Sort protocols, keyed by name.
3134 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3135
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003136 // Canonicalize.
3137 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3138 Protocols[I] = Protocols[I]->getCanonicalDecl();
3139
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003140 // Remove duplicates.
3141 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3142 NumProtocols = ProtocolsEnd-Protocols;
3143}
3144
John McCall8b07ec22010-05-15 11:32:37 +00003145QualType ASTContext::getObjCObjectType(QualType BaseType,
3146 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003147 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003148 // If the base type is an interface and there aren't any protocols
3149 // to add, then the interface type will do just fine.
3150 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3151 return BaseType;
3152
3153 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003154 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003155 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003156 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003157 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3158 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003159
John McCall8b07ec22010-05-15 11:32:37 +00003160 // Build the canonical type, which has the canonical base type and
3161 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003162 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003163 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3164 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3165 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003166 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003167 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003168 unsigned UniqueCount = NumProtocols;
3169
John McCallfc93cf92009-10-22 22:37:11 +00003170 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003171 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3172 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003173 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003174 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3175 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003176 }
3177
3178 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003179 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3180 }
3181
3182 unsigned Size = sizeof(ObjCObjectTypeImpl);
3183 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3184 void *Mem = Allocate(Size, TypeAlignment);
3185 ObjCObjectTypeImpl *T =
3186 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3187
3188 Types.push_back(T);
3189 ObjCObjectTypes.InsertNode(T, InsertPos);
3190 return QualType(T, 0);
3191}
3192
3193/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3194/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003195QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003196 llvm::FoldingSetNodeID ID;
3197 ObjCObjectPointerType::Profile(ID, ObjectT);
3198
3199 void *InsertPos = 0;
3200 if (ObjCObjectPointerType *QT =
3201 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3202 return QualType(QT, 0);
3203
3204 // Find the canonical object type.
3205 QualType Canonical;
3206 if (!ObjectT.isCanonical()) {
3207 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3208
3209 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003210 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3211 }
3212
Douglas Gregorf85bee62010-02-08 22:59:26 +00003213 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003214 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3215 ObjCObjectPointerType *QType =
3216 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003217
Steve Narofffb4330f2009-06-17 22:40:22 +00003218 Types.push_back(QType);
3219 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003220 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003221}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003222
Douglas Gregor1c283312010-08-11 12:19:30 +00003223/// getObjCInterfaceType - Return the unique reference to the type for the
3224/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003225QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3226 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003227 if (Decl->TypeForDecl)
3228 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003229
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003230 if (PrevDecl) {
3231 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3232 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3233 return QualType(PrevDecl->TypeForDecl, 0);
3234 }
3235
Douglas Gregor7671e532011-12-16 16:34:57 +00003236 // Prefer the definition, if there is one.
3237 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3238 Decl = Def;
3239
Douglas Gregor1c283312010-08-11 12:19:30 +00003240 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3241 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3242 Decl->TypeForDecl = T;
3243 Types.push_back(T);
3244 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003245}
3246
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003247/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3248/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003249/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003250/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003251/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003252QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003253 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003254 if (tofExpr->isTypeDependent()) {
3255 llvm::FoldingSetNodeID ID;
3256 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003257
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003258 void *InsertPos = 0;
3259 DependentTypeOfExprType *Canon
3260 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3261 if (Canon) {
3262 // We already have a "canonical" version of an identical, dependent
3263 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003264 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003265 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003266 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003267 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003268 Canon
3269 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003270 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3271 toe = Canon;
3272 }
3273 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003274 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003275 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003276 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003277 Types.push_back(toe);
3278 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003279}
3280
Steve Naroffa773cd52007-08-01 18:02:17 +00003281/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3282/// TypeOfType AST's. The only motivation to unique these nodes would be
3283/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003284/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003285/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003286QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003287 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003288 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003289 Types.push_back(tot);
3290 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003291}
3292
Anders Carlssonad6bd352009-06-24 21:24:56 +00003293
Anders Carlsson81df7b82009-06-24 19:06:50 +00003294/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3295/// DecltypeType AST's. The only motivation to unique these nodes would be
3296/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003297/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003298/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003299QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003300 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003301
3302 // C++0x [temp.type]p2:
3303 // If an expression e involves a template parameter, decltype(e) denotes a
3304 // unique dependent type. Two such decltype-specifiers refer to the same
3305 // type only if their expressions are equivalent (14.5.6.1).
3306 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003307 llvm::FoldingSetNodeID ID;
3308 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003309
Douglas Gregora21f6c32009-07-30 23:36:40 +00003310 void *InsertPos = 0;
3311 DependentDecltypeType *Canon
3312 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3313 if (Canon) {
3314 // We already have a "canonical" version of an equivalent, dependent
3315 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003316 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003317 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003318 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003319 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003320 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003321 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3322 dt = Canon;
3323 }
3324 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003325 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3326 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003327 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003328 Types.push_back(dt);
3329 return QualType(dt, 0);
3330}
3331
Alexis Hunte852b102011-05-24 22:41:36 +00003332/// getUnaryTransformationType - We don't unique these, since the memory
3333/// savings are minimal and these are rare.
3334QualType ASTContext::getUnaryTransformType(QualType BaseType,
3335 QualType UnderlyingType,
3336 UnaryTransformType::UTTKind Kind)
3337 const {
3338 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003339 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3340 Kind,
3341 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003342 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003343 Types.push_back(Ty);
3344 return QualType(Ty, 0);
3345}
3346
Richard Smithb2bc2e62011-02-21 20:05:19 +00003347/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003348QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003349 void *InsertPos = 0;
3350 if (!DeducedType.isNull()) {
3351 // Look in the folding set for an existing type.
3352 llvm::FoldingSetNodeID ID;
3353 AutoType::Profile(ID, DeducedType);
3354 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3355 return QualType(AT, 0);
3356 }
3357
3358 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3359 Types.push_back(AT);
3360 if (InsertPos)
3361 AutoTypes.InsertNode(AT, InsertPos);
3362 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003363}
3364
Eli Friedman0dfb8892011-10-06 23:00:33 +00003365/// getAtomicType - Return the uniqued reference to the atomic type for
3366/// the given value type.
3367QualType ASTContext::getAtomicType(QualType T) const {
3368 // Unique pointers, to guarantee there is only one pointer of a particular
3369 // structure.
3370 llvm::FoldingSetNodeID ID;
3371 AtomicType::Profile(ID, T);
3372
3373 void *InsertPos = 0;
3374 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3375 return QualType(AT, 0);
3376
3377 // If the atomic value type isn't canonical, this won't be a canonical type
3378 // either, so fill in the canonical type field.
3379 QualType Canonical;
3380 if (!T.isCanonical()) {
3381 Canonical = getAtomicType(getCanonicalType(T));
3382
3383 // Get the new insert position for the node we care about.
3384 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3385 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3386 }
3387 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3388 Types.push_back(New);
3389 AtomicTypes.InsertNode(New, InsertPos);
3390 return QualType(New, 0);
3391}
3392
Richard Smith02e85f32011-04-14 22:09:26 +00003393/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3394QualType ASTContext::getAutoDeductType() const {
3395 if (AutoDeductTy.isNull())
3396 AutoDeductTy = getAutoType(QualType());
3397 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3398 return AutoDeductTy;
3399}
3400
3401/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3402QualType ASTContext::getAutoRRefDeductType() const {
3403 if (AutoRRefDeductTy.isNull())
3404 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3405 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3406 return AutoRRefDeductTy;
3407}
3408
Chris Lattnerfb072462007-01-23 05:45:31 +00003409/// getTagDeclType - Return the unique reference to the type for the
3410/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003411QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003412 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003413 // FIXME: What is the design on getTagDeclType when it requires casting
3414 // away const? mutable?
3415 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003416}
3417
Mike Stump11289f42009-09-09 15:08:12 +00003418/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3419/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3420/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003421CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003422 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003423}
Chris Lattnerfb072462007-01-23 05:45:31 +00003424
Hans Wennborg27541db2011-10-27 08:29:09 +00003425/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3426CanQualType ASTContext::getIntMaxType() const {
3427 return getFromTargetType(Target->getIntMaxType());
3428}
3429
3430/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3431CanQualType ASTContext::getUIntMaxType() const {
3432 return getFromTargetType(Target->getUIntMaxType());
3433}
3434
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003435/// getSignedWCharType - Return the type of "signed wchar_t".
3436/// Used when in C++, as a GCC extension.
3437QualType ASTContext::getSignedWCharType() const {
3438 // FIXME: derive from "Target" ?
3439 return WCharTy;
3440}
3441
3442/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3443/// Used when in C++, as a GCC extension.
3444QualType ASTContext::getUnsignedWCharType() const {
3445 // FIXME: derive from "Target" ?
3446 return UnsignedIntTy;
3447}
3448
Hans Wennborg27541db2011-10-27 08:29:09 +00003449/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003450/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3451QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003452 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003453}
3454
Chris Lattnera21ad802008-04-02 05:18:44 +00003455//===----------------------------------------------------------------------===//
3456// Type Operators
3457//===----------------------------------------------------------------------===//
3458
Jay Foad39c79802011-01-12 09:06:06 +00003459CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003460 // Push qualifiers into arrays, and then discard any remaining
3461 // qualifiers.
3462 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003463 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003464 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003465 QualType Result;
3466 if (isa<ArrayType>(Ty)) {
3467 Result = getArrayDecayedType(QualType(Ty,0));
3468 } else if (isa<FunctionType>(Ty)) {
3469 Result = getPointerType(QualType(Ty, 0));
3470 } else {
3471 Result = QualType(Ty, 0);
3472 }
3473
3474 return CanQualType::CreateUnsafe(Result);
3475}
3476
John McCall6c9dd522011-01-18 07:41:22 +00003477QualType ASTContext::getUnqualifiedArrayType(QualType type,
3478 Qualifiers &quals) {
3479 SplitQualType splitType = type.getSplitUnqualifiedType();
3480
3481 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3482 // the unqualified desugared type and then drops it on the floor.
3483 // We then have to strip that sugar back off with
3484 // getUnqualifiedDesugaredType(), which is silly.
3485 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003486 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003487
3488 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003489 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003490 quals = splitType.Quals;
3491 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003492 }
3493
John McCall6c9dd522011-01-18 07:41:22 +00003494 // Otherwise, recurse on the array's element type.
3495 QualType elementType = AT->getElementType();
3496 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3497
3498 // If that didn't change the element type, AT has no qualifiers, so we
3499 // can just use the results in splitType.
3500 if (elementType == unqualElementType) {
3501 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003502 quals = splitType.Quals;
3503 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003504 }
3505
3506 // Otherwise, add in the qualifiers from the outermost type, then
3507 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003508 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003509
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003510 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003511 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003512 CAT->getSizeModifier(), 0);
3513 }
3514
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003515 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003516 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003517 }
3518
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003519 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003520 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003521 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003522 VAT->getSizeModifier(),
3523 VAT->getIndexTypeCVRQualifiers(),
3524 VAT->getBracketsRange());
3525 }
3526
3527 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003528 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003529 DSAT->getSizeModifier(), 0,
3530 SourceRange());
3531}
3532
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003533/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3534/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3535/// they point to and return true. If T1 and T2 aren't pointer types
3536/// or pointer-to-member types, or if they are not similar at this
3537/// level, returns false and leaves T1 and T2 unchanged. Top-level
3538/// qualifiers on T1 and T2 are ignored. This function will typically
3539/// be called in a loop that successively "unwraps" pointer and
3540/// pointer-to-member types to compare them at each level.
3541bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3542 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3543 *T2PtrType = T2->getAs<PointerType>();
3544 if (T1PtrType && T2PtrType) {
3545 T1 = T1PtrType->getPointeeType();
3546 T2 = T2PtrType->getPointeeType();
3547 return true;
3548 }
3549
3550 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3551 *T2MPType = T2->getAs<MemberPointerType>();
3552 if (T1MPType && T2MPType &&
3553 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3554 QualType(T2MPType->getClass(), 0))) {
3555 T1 = T1MPType->getPointeeType();
3556 T2 = T2MPType->getPointeeType();
3557 return true;
3558 }
3559
David Blaikiebbafb8a2012-03-11 07:00:24 +00003560 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003561 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3562 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3563 if (T1OPType && T2OPType) {
3564 T1 = T1OPType->getPointeeType();
3565 T2 = T2OPType->getPointeeType();
3566 return true;
3567 }
3568 }
3569
3570 // FIXME: Block pointers, too?
3571
3572 return false;
3573}
3574
Jay Foad39c79802011-01-12 09:06:06 +00003575DeclarationNameInfo
3576ASTContext::getNameForTemplate(TemplateName Name,
3577 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003578 switch (Name.getKind()) {
3579 case TemplateName::QualifiedTemplate:
3580 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003581 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003582 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3583 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003584
John McCalld9dfe3a2011-06-30 08:33:18 +00003585 case TemplateName::OverloadedTemplate: {
3586 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3587 // DNInfo work in progress: CHECKME: what about DNLoc?
3588 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3589 }
3590
3591 case TemplateName::DependentTemplate: {
3592 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003593 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003594 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003595 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3596 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003597 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003598 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3599 // DNInfo work in progress: FIXME: source locations?
3600 DeclarationNameLoc DNLoc;
3601 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3602 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3603 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003604 }
3605 }
3606
John McCalld9dfe3a2011-06-30 08:33:18 +00003607 case TemplateName::SubstTemplateTemplateParm: {
3608 SubstTemplateTemplateParmStorage *subst
3609 = Name.getAsSubstTemplateTemplateParm();
3610 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3611 NameLoc);
3612 }
3613
3614 case TemplateName::SubstTemplateTemplateParmPack: {
3615 SubstTemplateTemplateParmPackStorage *subst
3616 = Name.getAsSubstTemplateTemplateParmPack();
3617 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3618 NameLoc);
3619 }
3620 }
3621
3622 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003623}
3624
Jay Foad39c79802011-01-12 09:06:06 +00003625TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003626 switch (Name.getKind()) {
3627 case TemplateName::QualifiedTemplate:
3628 case TemplateName::Template: {
3629 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003630 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003631 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003632 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3633
3634 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003635 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003636 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003637
John McCalld9dfe3a2011-06-30 08:33:18 +00003638 case TemplateName::OverloadedTemplate:
3639 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003640
John McCalld9dfe3a2011-06-30 08:33:18 +00003641 case TemplateName::DependentTemplate: {
3642 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3643 assert(DTN && "Non-dependent template names must refer to template decls.");
3644 return DTN->CanonicalTemplateName;
3645 }
3646
3647 case TemplateName::SubstTemplateTemplateParm: {
3648 SubstTemplateTemplateParmStorage *subst
3649 = Name.getAsSubstTemplateTemplateParm();
3650 return getCanonicalTemplateName(subst->getReplacement());
3651 }
3652
3653 case TemplateName::SubstTemplateTemplateParmPack: {
3654 SubstTemplateTemplateParmPackStorage *subst
3655 = Name.getAsSubstTemplateTemplateParmPack();
3656 TemplateTemplateParmDecl *canonParameter
3657 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3658 TemplateArgument canonArgPack
3659 = getCanonicalTemplateArgument(subst->getArgumentPack());
3660 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3661 }
3662 }
3663
3664 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003665}
3666
Douglas Gregoradee3e32009-11-11 23:06:43 +00003667bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3668 X = getCanonicalTemplateName(X);
3669 Y = getCanonicalTemplateName(Y);
3670 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3671}
3672
Mike Stump11289f42009-09-09 15:08:12 +00003673TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003674ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003675 switch (Arg.getKind()) {
3676 case TemplateArgument::Null:
3677 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003678
Douglas Gregora8e02e72009-07-28 23:00:59 +00003679 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003680 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003681
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003682 case TemplateArgument::Declaration: {
3683 if (Decl *D = Arg.getAsDecl())
3684 return TemplateArgument(D->getCanonicalDecl());
3685 return TemplateArgument((Decl*)0);
3686 }
Mike Stump11289f42009-09-09 15:08:12 +00003687
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003688 case TemplateArgument::Template:
3689 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003690
3691 case TemplateArgument::TemplateExpansion:
3692 return TemplateArgument(getCanonicalTemplateName(
3693 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003694 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003695
Douglas Gregora8e02e72009-07-28 23:00:59 +00003696 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003697 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003698
Douglas Gregora8e02e72009-07-28 23:00:59 +00003699 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003700 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003701
Douglas Gregora8e02e72009-07-28 23:00:59 +00003702 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003703 if (Arg.pack_size() == 0)
3704 return Arg;
3705
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003706 TemplateArgument *CanonArgs
3707 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003708 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003709 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003710 AEnd = Arg.pack_end();
3711 A != AEnd; (void)++A, ++Idx)
3712 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003713
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003714 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003715 }
3716 }
3717
3718 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003719 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003720}
3721
Douglas Gregor333489b2009-03-27 23:10:48 +00003722NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003723ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003724 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003725 return 0;
3726
3727 switch (NNS->getKind()) {
3728 case NestedNameSpecifier::Identifier:
3729 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003730 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003731 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3732 NNS->getAsIdentifier());
3733
3734 case NestedNameSpecifier::Namespace:
3735 // A namespace is canonical; build a nested-name-specifier with
3736 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003737 return NestedNameSpecifier::Create(*this, 0,
3738 NNS->getAsNamespace()->getOriginalNamespace());
3739
3740 case NestedNameSpecifier::NamespaceAlias:
3741 // A namespace is canonical; build a nested-name-specifier with
3742 // this namespace and no prefix.
3743 return NestedNameSpecifier::Create(*this, 0,
3744 NNS->getAsNamespaceAlias()->getNamespace()
3745 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003746
3747 case NestedNameSpecifier::TypeSpec:
3748 case NestedNameSpecifier::TypeSpecWithTemplate: {
3749 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003750
3751 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3752 // break it apart into its prefix and identifier, then reconsititute those
3753 // as the canonical nested-name-specifier. This is required to canonicalize
3754 // a dependent nested-name-specifier involving typedefs of dependent-name
3755 // types, e.g.,
3756 // typedef typename T::type T1;
3757 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003758 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3759 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003760 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003761
Eli Friedman5358a0a2012-03-03 04:09:56 +00003762 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3763 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3764 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003765 return NestedNameSpecifier::Create(*this, 0, false,
3766 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003767 }
3768
3769 case NestedNameSpecifier::Global:
3770 // The global specifier is canonical and unique.
3771 return NNS;
3772 }
3773
David Blaikie8a40f702012-01-17 06:56:22 +00003774 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003775}
3776
Chris Lattner7adf0762008-08-04 07:31:14 +00003777
Jay Foad39c79802011-01-12 09:06:06 +00003778const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003779 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003780 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003781 // Handle the common positive case fast.
3782 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3783 return AT;
3784 }
Mike Stump11289f42009-09-09 15:08:12 +00003785
John McCall8ccfcb52009-09-24 19:53:00 +00003786 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003787 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003788 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003789
John McCall8ccfcb52009-09-24 19:53:00 +00003790 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003791 // implements C99 6.7.3p8: "If the specification of an array type includes
3792 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003793
Chris Lattner7adf0762008-08-04 07:31:14 +00003794 // If we get here, we either have type qualifiers on the type, or we have
3795 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003796 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003797
John McCall33ddac02011-01-19 10:06:00 +00003798 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003799 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003800
Chris Lattner7adf0762008-08-04 07:31:14 +00003801 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003802 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003803 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003804 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003805
Chris Lattner7adf0762008-08-04 07:31:14 +00003806 // Otherwise, we have an array and we have qualifiers on it. Push the
3807 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003808 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003809
Chris Lattner7adf0762008-08-04 07:31:14 +00003810 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3811 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3812 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003813 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003814 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3815 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3816 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003817 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003818
Mike Stump11289f42009-09-09 15:08:12 +00003819 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003820 = dyn_cast<DependentSizedArrayType>(ATy))
3821 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003822 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003823 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003824 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003825 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003826 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003827
Chris Lattner7adf0762008-08-04 07:31:14 +00003828 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003829 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003830 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003831 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003832 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003833 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003834}
3835
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003836QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003837 // C99 6.7.5.3p7:
3838 // A declaration of a parameter as "array of type" shall be
3839 // adjusted to "qualified pointer to type", where the type
3840 // qualifiers (if any) are those specified within the [ and ] of
3841 // the array type derivation.
3842 if (T->isArrayType())
3843 return getArrayDecayedType(T);
3844
3845 // C99 6.7.5.3p8:
3846 // A declaration of a parameter as "function returning type"
3847 // shall be adjusted to "pointer to function returning type", as
3848 // in 6.3.2.1.
3849 if (T->isFunctionType())
3850 return getPointerType(T);
3851
3852 return T;
3853}
3854
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003855QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003856 T = getVariableArrayDecayedType(T);
3857 T = getAdjustedParameterType(T);
3858 return T.getUnqualifiedType();
3859}
3860
Chris Lattnera21ad802008-04-02 05:18:44 +00003861/// getArrayDecayedType - Return the properly qualified result of decaying the
3862/// specified array type to a pointer. This operation is non-trivial when
3863/// handling typedefs etc. The canonical type of "T" must be an array type,
3864/// this returns a pointer to a properly qualified element of the array.
3865///
3866/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003867QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003868 // Get the element type with 'getAsArrayType' so that we don't lose any
3869 // typedefs in the element type of the array. This also handles propagation
3870 // of type qualifiers from the array type into the element type if present
3871 // (C99 6.7.3p8).
3872 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3873 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003874
Chris Lattner7adf0762008-08-04 07:31:14 +00003875 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003876
3877 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003878 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003879}
3880
John McCall33ddac02011-01-19 10:06:00 +00003881QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3882 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003883}
3884
John McCall33ddac02011-01-19 10:06:00 +00003885QualType ASTContext::getBaseElementType(QualType type) const {
3886 Qualifiers qs;
3887 while (true) {
3888 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003889 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003890 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003891
John McCall33ddac02011-01-19 10:06:00 +00003892 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003893 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003894 }
Mike Stump11289f42009-09-09 15:08:12 +00003895
John McCall33ddac02011-01-19 10:06:00 +00003896 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003897}
3898
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003899/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003900uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003901ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3902 uint64_t ElementCount = 1;
3903 do {
3904 ElementCount *= CA->getSize().getZExtValue();
3905 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3906 } while (CA);
3907 return ElementCount;
3908}
3909
Steve Naroff0af91202007-04-27 21:51:21 +00003910/// getFloatingRank - Return a relative rank for floating point types.
3911/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003912static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003913 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003914 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003915
John McCall9dd450b2009-09-21 23:43:11 +00003916 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3917 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003918 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003919 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003920 case BuiltinType::Float: return FloatRank;
3921 case BuiltinType::Double: return DoubleRank;
3922 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003923 }
3924}
3925
Mike Stump11289f42009-09-09 15:08:12 +00003926/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3927/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003928/// 'typeDomain' is a real floating point or complex type.
3929/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003930QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3931 QualType Domain) const {
3932 FloatingRank EltRank = getFloatingRank(Size);
3933 if (Domain->isComplexType()) {
3934 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003935 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003936 case FloatRank: return FloatComplexTy;
3937 case DoubleRank: return DoubleComplexTy;
3938 case LongDoubleRank: return LongDoubleComplexTy;
3939 }
Steve Naroff0af91202007-04-27 21:51:21 +00003940 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003941
3942 assert(Domain->isRealFloatingType() && "Unknown domain!");
3943 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003944 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003945 case FloatRank: return FloatTy;
3946 case DoubleRank: return DoubleTy;
3947 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003948 }
David Blaikief47fa302012-01-17 02:30:50 +00003949 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003950}
3951
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003952/// getFloatingTypeOrder - Compare the rank of the two specified floating
3953/// point types, ignoring the domain of the type (i.e. 'double' ==
3954/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003955/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003956int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003957 FloatingRank LHSR = getFloatingRank(LHS);
3958 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003959
Chris Lattnerb90739d2008-04-06 23:38:49 +00003960 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003961 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003962 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003963 return 1;
3964 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003965}
3966
Chris Lattner76a00cf2008-04-06 22:59:24 +00003967/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3968/// routine will assert if passed a built-in type that isn't an integer or enum,
3969/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003970unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003971 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003972
Chris Lattner76a00cf2008-04-06 22:59:24 +00003973 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003974 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003975 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003976 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003977 case BuiltinType::Char_S:
3978 case BuiltinType::Char_U:
3979 case BuiltinType::SChar:
3980 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003981 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003982 case BuiltinType::Short:
3983 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003984 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003985 case BuiltinType::Int:
3986 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003987 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003988 case BuiltinType::Long:
3989 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003990 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003991 case BuiltinType::LongLong:
3992 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003993 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003994 case BuiltinType::Int128:
3995 case BuiltinType::UInt128:
3996 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003997 }
3998}
3999
Eli Friedman629ffb92009-08-20 04:21:42 +00004000/// \brief Whether this is a promotable bitfield reference according
4001/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4002///
4003/// \returns the type this bit-field will promote to, or NULL if no
4004/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004005QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004006 if (E->isTypeDependent() || E->isValueDependent())
4007 return QualType();
4008
Eli Friedman629ffb92009-08-20 04:21:42 +00004009 FieldDecl *Field = E->getBitField();
4010 if (!Field)
4011 return QualType();
4012
4013 QualType FT = Field->getType();
4014
Richard Smithcaf33902011-10-10 18:28:20 +00004015 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004016 uint64_t IntSize = getTypeSize(IntTy);
4017 // GCC extension compatibility: if the bit-field size is less than or equal
4018 // to the size of int, it gets promoted no matter what its type is.
4019 // For instance, unsigned long bf : 4 gets promoted to signed int.
4020 if (BitWidth < IntSize)
4021 return IntTy;
4022
4023 if (BitWidth == IntSize)
4024 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4025
4026 // Types bigger than int are not subject to promotions, and therefore act
4027 // like the base type.
4028 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4029 // is ridiculous.
4030 return QualType();
4031}
4032
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004033/// getPromotedIntegerType - Returns the type that Promotable will
4034/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4035/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004036QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004037 assert(!Promotable.isNull());
4038 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004039 if (const EnumType *ET = Promotable->getAs<EnumType>())
4040 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004041
4042 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4043 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4044 // (3.9.1) can be converted to a prvalue of the first of the following
4045 // types that can represent all the values of its underlying type:
4046 // int, unsigned int, long int, unsigned long int, long long int, or
4047 // unsigned long long int [...]
4048 // FIXME: Is there some better way to compute this?
4049 if (BT->getKind() == BuiltinType::WChar_S ||
4050 BT->getKind() == BuiltinType::WChar_U ||
4051 BT->getKind() == BuiltinType::Char16 ||
4052 BT->getKind() == BuiltinType::Char32) {
4053 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4054 uint64_t FromSize = getTypeSize(BT);
4055 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4056 LongLongTy, UnsignedLongLongTy };
4057 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4058 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4059 if (FromSize < ToSize ||
4060 (FromSize == ToSize &&
4061 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4062 return PromoteTypes[Idx];
4063 }
4064 llvm_unreachable("char type should fit into long long");
4065 }
4066 }
4067
4068 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004069 if (Promotable->isSignedIntegerType())
4070 return IntTy;
4071 uint64_t PromotableSize = getTypeSize(Promotable);
4072 uint64_t IntSize = getTypeSize(IntTy);
4073 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4074 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4075}
4076
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004077/// \brief Recurses in pointer/array types until it finds an objc retainable
4078/// type and returns its ownership.
4079Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4080 while (!T.isNull()) {
4081 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4082 return T.getObjCLifetime();
4083 if (T->isArrayType())
4084 T = getBaseElementType(T);
4085 else if (const PointerType *PT = T->getAs<PointerType>())
4086 T = PT->getPointeeType();
4087 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004088 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004089 else
4090 break;
4091 }
4092
4093 return Qualifiers::OCL_None;
4094}
4095
Mike Stump11289f42009-09-09 15:08:12 +00004096/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004097/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004098/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004099int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004100 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4101 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004102 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004103
Chris Lattner76a00cf2008-04-06 22:59:24 +00004104 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4105 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004106
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004107 unsigned LHSRank = getIntegerRank(LHSC);
4108 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004109
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004110 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4111 if (LHSRank == RHSRank) return 0;
4112 return LHSRank > RHSRank ? 1 : -1;
4113 }
Mike Stump11289f42009-09-09 15:08:12 +00004114
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004115 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4116 if (LHSUnsigned) {
4117 // If the unsigned [LHS] type is larger, return it.
4118 if (LHSRank >= RHSRank)
4119 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004120
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004121 // If the signed type can represent all values of the unsigned type, it
4122 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004123 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004124 return -1;
4125 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004126
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004127 // If the unsigned [RHS] type is larger, return it.
4128 if (RHSRank >= LHSRank)
4129 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004130
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004131 // If the signed type can represent all values of the unsigned type, it
4132 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004133 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004134 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004135}
Anders Carlsson98f07902007-08-17 05:31:46 +00004136
Anders Carlsson6d417272009-11-14 21:45:58 +00004137static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004138CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4139 DeclContext *DC, IdentifierInfo *Id) {
4140 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004141 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004142 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004143 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004144 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004145}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004146
Mike Stump11289f42009-09-09 15:08:12 +00004147// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004148QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004149 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004150 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004151 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004152 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004153 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004154
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004155 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004156
Anders Carlsson98f07902007-08-17 05:31:46 +00004157 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004158 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004159 // int flags;
4160 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004161 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004162 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004163 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004164 FieldTypes[3] = LongTy;
4165
Anders Carlsson98f07902007-08-17 05:31:46 +00004166 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004167 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004168 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004169 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004170 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004171 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004172 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004173 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004174 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004175 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004176 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004177 }
4178
Douglas Gregord5058122010-02-11 01:19:42 +00004179 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004180 }
Mike Stump11289f42009-09-09 15:08:12 +00004181
Anders Carlsson98f07902007-08-17 05:31:46 +00004182 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004183}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004184
Douglas Gregor512b0772009-04-23 22:29:11 +00004185void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004186 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004187 assert(Rec && "Invalid CFConstantStringType");
4188 CFConstantStringTypeDecl = Rec->getDecl();
4189}
4190
Jay Foad39c79802011-01-12 09:06:06 +00004191QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004192 if (BlockDescriptorType)
4193 return getTagDeclType(BlockDescriptorType);
4194
4195 RecordDecl *T;
4196 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004197 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004198 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004199 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004200
4201 QualType FieldTypes[] = {
4202 UnsignedLongTy,
4203 UnsignedLongTy,
4204 };
4205
4206 const char *FieldNames[] = {
4207 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004208 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004209 };
4210
4211 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004212 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004213 SourceLocation(),
4214 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004215 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004216 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004217 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004218 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004219 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004220 T->addDecl(Field);
4221 }
4222
Douglas Gregord5058122010-02-11 01:19:42 +00004223 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004224
4225 BlockDescriptorType = T;
4226
4227 return getTagDeclType(BlockDescriptorType);
4228}
4229
Jay Foad39c79802011-01-12 09:06:06 +00004230QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004231 if (BlockDescriptorExtendedType)
4232 return getTagDeclType(BlockDescriptorExtendedType);
4233
4234 RecordDecl *T;
4235 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004236 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004237 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004238 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004239
4240 QualType FieldTypes[] = {
4241 UnsignedLongTy,
4242 UnsignedLongTy,
4243 getPointerType(VoidPtrTy),
4244 getPointerType(VoidPtrTy)
4245 };
4246
4247 const char *FieldNames[] = {
4248 "reserved",
4249 "Size",
4250 "CopyFuncPtr",
4251 "DestroyFuncPtr"
4252 };
4253
4254 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004255 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004256 SourceLocation(),
4257 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004258 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004259 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004260 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004261 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004262 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004263 T->addDecl(Field);
4264 }
4265
Douglas Gregord5058122010-02-11 01:19:42 +00004266 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004267
4268 BlockDescriptorExtendedType = T;
4269
4270 return getTagDeclType(BlockDescriptorExtendedType);
4271}
4272
Jay Foad39c79802011-01-12 09:06:06 +00004273bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00004274 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00004275 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004276 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004277 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4278 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00004279 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004280
4281 }
4282 }
Mike Stump94967902009-10-21 18:16:27 +00004283 return false;
4284}
4285
Jay Foad39c79802011-01-12 09:06:06 +00004286QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004287ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00004288 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00004289 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00004290 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004291 // unsigned int __flags;
4292 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00004293 // void *__copy_helper; // as needed
4294 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00004295 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00004296 // } *
4297
Mike Stump94967902009-10-21 18:16:27 +00004298 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4299
4300 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004301 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00004302 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4303 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00004304 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004305 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00004306 T->startDefinition();
4307 QualType Int32Ty = IntTy;
4308 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4309 QualType FieldTypes[] = {
4310 getPointerType(VoidPtrTy),
4311 getPointerType(getTagDeclType(T)),
4312 Int32Ty,
4313 Int32Ty,
4314 getPointerType(VoidPtrTy),
4315 getPointerType(VoidPtrTy),
4316 Ty
4317 };
4318
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004319 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00004320 "__isa",
4321 "__forwarding",
4322 "__flags",
4323 "__size",
4324 "__copy_helper",
4325 "__destroy_helper",
4326 DeclName,
4327 };
4328
4329 for (size_t i = 0; i < 7; ++i) {
4330 if (!HasCopyAndDispose && i >=4 && i <= 5)
4331 continue;
4332 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004333 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00004334 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004335 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004336 /*BitWidth=*/0, /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004337 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004338 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00004339 T->addDecl(Field);
4340 }
4341
Douglas Gregord5058122010-02-11 01:19:42 +00004342 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00004343
4344 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00004345}
4346
Douglas Gregorbab8a962011-09-08 01:46:34 +00004347TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4348 if (!ObjCInstanceTypeDecl)
4349 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4350 getTranslationUnitDecl(),
4351 SourceLocation(),
4352 SourceLocation(),
4353 &Idents.get("instancetype"),
4354 getTrivialTypeSourceInfo(getObjCIdType()));
4355 return ObjCInstanceTypeDecl;
4356}
4357
Anders Carlsson18acd442007-10-29 06:33:42 +00004358// This returns true if a type has been typedefed to BOOL:
4359// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004360static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004361 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004362 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4363 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004364
Anders Carlssond8499822007-10-29 05:01:08 +00004365 return false;
4366}
4367
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004368/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004369/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004370CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004371 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4372 return CharUnits::Zero();
4373
Ken Dyck40775002010-01-11 17:06:35 +00004374 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004375
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004376 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004377 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004378 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004379 // Treat arrays as pointers, since that's how they're passed in.
4380 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004381 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004382 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004383}
4384
4385static inline
4386std::string charUnitsToString(const CharUnits &CU) {
4387 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004388}
4389
John McCall351762c2011-02-07 10:33:21 +00004390/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004391/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004392std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4393 std::string S;
4394
David Chisnall950a9512009-11-17 19:33:30 +00004395 const BlockDecl *Decl = Expr->getBlockDecl();
4396 QualType BlockTy =
4397 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4398 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004399 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004400 // Compute size of all parameters.
4401 // Start with computing size of a pointer in number of bytes.
4402 // FIXME: There might(should) be a better way of doing this computation!
4403 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004404 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4405 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004406 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004407 E = Decl->param_end(); PI != E; ++PI) {
4408 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004409 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004410 if (sz.isZero())
4411 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004412 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004413 ParmOffset += sz;
4414 }
4415 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004416 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004417 // Block pointer and offset.
4418 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004419
4420 // Argument types.
4421 ParmOffset = PtrSize;
4422 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4423 Decl->param_end(); PI != E; ++PI) {
4424 ParmVarDecl *PVDecl = *PI;
4425 QualType PType = PVDecl->getOriginalType();
4426 if (const ArrayType *AT =
4427 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4428 // Use array's original type only if it has known number of
4429 // elements.
4430 if (!isa<ConstantArrayType>(AT))
4431 PType = PVDecl->getType();
4432 } else if (PType->isFunctionType())
4433 PType = PVDecl->getType();
4434 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004435 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004436 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004437 }
John McCall351762c2011-02-07 10:33:21 +00004438
4439 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004440}
4441
Douglas Gregora9d84932011-05-27 01:19:52 +00004442bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004443 std::string& S) {
4444 // Encode result type.
4445 getObjCEncodingForType(Decl->getResultType(), S);
4446 CharUnits ParmOffset;
4447 // Compute size of all parameters.
4448 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4449 E = Decl->param_end(); PI != E; ++PI) {
4450 QualType PType = (*PI)->getType();
4451 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004452 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004453 continue;
4454
David Chisnall50e4eba2010-12-30 14:05:53 +00004455 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004456 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004457 ParmOffset += sz;
4458 }
4459 S += charUnitsToString(ParmOffset);
4460 ParmOffset = CharUnits::Zero();
4461
4462 // Argument types.
4463 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4464 E = Decl->param_end(); PI != E; ++PI) {
4465 ParmVarDecl *PVDecl = *PI;
4466 QualType PType = PVDecl->getOriginalType();
4467 if (const ArrayType *AT =
4468 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4469 // Use array's original type only if it has known number of
4470 // elements.
4471 if (!isa<ConstantArrayType>(AT))
4472 PType = PVDecl->getType();
4473 } else if (PType->isFunctionType())
4474 PType = PVDecl->getType();
4475 getObjCEncodingForType(PType, S);
4476 S += charUnitsToString(ParmOffset);
4477 ParmOffset += getObjCEncodingTypeSize(PType);
4478 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004479
4480 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004481}
4482
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004483/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4484/// method parameter or return type. If Extended, include class names and
4485/// block object types.
4486void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4487 QualType T, std::string& S,
4488 bool Extended) const {
4489 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4490 getObjCEncodingForTypeQualifier(QT, S);
4491 // Encode parameter type.
4492 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4493 true /*OutermostType*/,
4494 false /*EncodingProperty*/,
4495 false /*StructField*/,
4496 Extended /*EncodeBlockParameters*/,
4497 Extended /*EncodeClassNames*/);
4498}
4499
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004500/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004501/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004502bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004503 std::string& S,
4504 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004505 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004506 // Encode return type.
4507 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4508 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004509 // Compute size of all parameters.
4510 // Start with computing size of a pointer in number of bytes.
4511 // FIXME: There might(should) be a better way of doing this computation!
4512 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004513 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004514 // The first two arguments (self and _cmd) are pointers; account for
4515 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004516 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004517 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004518 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004519 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004520 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004521 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004522 continue;
4523
Ken Dyck40775002010-01-11 17:06:35 +00004524 assert (sz.isPositive() &&
4525 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004526 ParmOffset += sz;
4527 }
Ken Dyck40775002010-01-11 17:06:35 +00004528 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004529 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004530 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004531
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004532 // Argument types.
4533 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004534 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004535 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004536 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004537 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004538 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004539 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4540 // Use array's original type only if it has known number of
4541 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004542 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004543 PType = PVDecl->getType();
4544 } else if (PType->isFunctionType())
4545 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004546 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4547 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004548 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004549 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004550 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004551
4552 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004553}
4554
Daniel Dunbar4932b362008-08-28 04:38:10 +00004555/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004556/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004557/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4558/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004559/// Property attributes are stored as a comma-delimited C string. The simple
4560/// attributes readonly and bycopy are encoded as single characters. The
4561/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4562/// encoded as single characters, followed by an identifier. Property types
4563/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004564/// these attributes are defined by the following enumeration:
4565/// @code
4566/// enum PropertyAttributes {
4567/// kPropertyReadOnly = 'R', // property is read-only.
4568/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4569/// kPropertyByref = '&', // property is a reference to the value last assigned
4570/// kPropertyDynamic = 'D', // property is dynamic
4571/// kPropertyGetter = 'G', // followed by getter selector name
4572/// kPropertySetter = 'S', // followed by setter selector name
4573/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004574/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004575/// kPropertyWeak = 'W' // 'weak' property
4576/// kPropertyStrong = 'P' // property GC'able
4577/// kPropertyNonAtomic = 'N' // property non-atomic
4578/// };
4579/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004580void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004581 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004582 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004583 // Collect information from the property implementation decl(s).
4584 bool Dynamic = false;
4585 ObjCPropertyImplDecl *SynthesizePID = 0;
4586
4587 // FIXME: Duplicated code due to poor abstraction.
4588 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004589 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004590 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4591 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004592 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004593 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004594 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004595 if (PID->getPropertyDecl() == PD) {
4596 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4597 Dynamic = true;
4598 } else {
4599 SynthesizePID = PID;
4600 }
4601 }
4602 }
4603 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004604 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004605 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004606 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004607 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004608 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004609 if (PID->getPropertyDecl() == PD) {
4610 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4611 Dynamic = true;
4612 } else {
4613 SynthesizePID = PID;
4614 }
4615 }
Mike Stump11289f42009-09-09 15:08:12 +00004616 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004617 }
4618 }
4619
4620 // FIXME: This is not very efficient.
4621 S = "T";
4622
4623 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004624 // GCC has some special rules regarding encoding of properties which
4625 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004626 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004627 true /* outermost type */,
4628 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004629
4630 if (PD->isReadOnly()) {
4631 S += ",R";
4632 } else {
4633 switch (PD->getSetterKind()) {
4634 case ObjCPropertyDecl::Assign: break;
4635 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004636 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004637 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004638 }
4639 }
4640
4641 // It really isn't clear at all what this means, since properties
4642 // are "dynamic by default".
4643 if (Dynamic)
4644 S += ",D";
4645
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004646 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4647 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004648
Daniel Dunbar4932b362008-08-28 04:38:10 +00004649 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4650 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004651 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004652 }
4653
4654 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4655 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004656 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004657 }
4658
4659 if (SynthesizePID) {
4660 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4661 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004662 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004663 }
4664
4665 // FIXME: OBJCGC: weak & strong
4666}
4667
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004668/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004669/// Another legacy compatibility encoding: 32-bit longs are encoded as
4670/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004671/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4672///
4673void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004674 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004675 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004676 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004677 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004678 else
Jay Foad39c79802011-01-12 09:06:06 +00004679 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004680 PointeeTy = IntTy;
4681 }
4682 }
4683}
4684
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004685void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004686 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004687 // We follow the behavior of gcc, expanding structures which are
4688 // directly pointed to, and expanding embedded structures. Note that
4689 // these rules are sufficient to prevent recursive encoding of the
4690 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004691 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004692 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004693}
4694
David Chisnallb190a2c2010-06-04 01:10:52 +00004695static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4696 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004697 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004698 case BuiltinType::Void: return 'v';
4699 case BuiltinType::Bool: return 'B';
4700 case BuiltinType::Char_U:
4701 case BuiltinType::UChar: return 'C';
4702 case BuiltinType::UShort: return 'S';
4703 case BuiltinType::UInt: return 'I';
4704 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004705 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004706 case BuiltinType::UInt128: return 'T';
4707 case BuiltinType::ULongLong: return 'Q';
4708 case BuiltinType::Char_S:
4709 case BuiltinType::SChar: return 'c';
4710 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004711 case BuiltinType::WChar_S:
4712 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004713 case BuiltinType::Int: return 'i';
4714 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004715 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004716 case BuiltinType::LongLong: return 'q';
4717 case BuiltinType::Int128: return 't';
4718 case BuiltinType::Float: return 'f';
4719 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004720 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004721 }
4722}
4723
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004724static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4725 EnumDecl *Enum = ET->getDecl();
4726
4727 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4728 if (!Enum->isFixed())
4729 return 'i';
4730
4731 // The encoding of a fixed enum type matches its fixed underlying type.
4732 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4733}
4734
Jay Foad39c79802011-01-12 09:06:06 +00004735static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004736 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004737 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004738 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004739 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4740 // The GNU runtime requires more information; bitfields are encoded as b,
4741 // then the offset (in bits) of the first element, then the type of the
4742 // bitfield, then the size in bits. For example, in this structure:
4743 //
4744 // struct
4745 // {
4746 // int integer;
4747 // int flags:2;
4748 // };
4749 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4750 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4751 // information is not especially sensible, but we're stuck with it for
4752 // compatibility with GCC, although providing it breaks anything that
4753 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004754 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004755 const RecordDecl *RD = FD->getParent();
4756 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004757 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004758 if (const EnumType *ET = T->getAs<EnumType>())
4759 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004760 else
Jay Foad39c79802011-01-12 09:06:06 +00004761 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004762 }
Richard Smithcaf33902011-10-10 18:28:20 +00004763 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004764}
4765
Daniel Dunbar07d07852009-10-18 21:17:35 +00004766// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004767void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4768 bool ExpandPointedToStructures,
4769 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004770 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004771 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004772 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004773 bool StructField,
4774 bool EncodeBlockParameters,
4775 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004776 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004777 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004778 return EncodeBitField(this, S, T, FD);
4779 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004780 return;
4781 }
Mike Stump11289f42009-09-09 15:08:12 +00004782
John McCall9dd450b2009-09-21 23:43:11 +00004783 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004784 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004785 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004786 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004787 return;
4788 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004789
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004790 // encoding for pointer or r3eference types.
4791 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004792 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004793 if (PT->isObjCSelType()) {
4794 S += ':';
4795 return;
4796 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004797 PointeeTy = PT->getPointeeType();
4798 }
4799 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4800 PointeeTy = RT->getPointeeType();
4801 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004802 bool isReadOnly = false;
4803 // For historical/compatibility reasons, the read-only qualifier of the
4804 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4805 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004806 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004807 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004808 if (OutermostType && T.isConstQualified()) {
4809 isReadOnly = true;
4810 S += 'r';
4811 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004812 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004813 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004814 while (P->getAs<PointerType>())
4815 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004816 if (P.isConstQualified()) {
4817 isReadOnly = true;
4818 S += 'r';
4819 }
4820 }
4821 if (isReadOnly) {
4822 // Another legacy compatibility encoding. Some ObjC qualifier and type
4823 // combinations need to be rearranged.
4824 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004825 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004826 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004827 }
Mike Stump11289f42009-09-09 15:08:12 +00004828
Anders Carlssond8499822007-10-29 05:01:08 +00004829 if (PointeeTy->isCharType()) {
4830 // char pointer types should be encoded as '*' unless it is a
4831 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004832 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004833 S += '*';
4834 return;
4835 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004836 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004837 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4838 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4839 S += '#';
4840 return;
4841 }
4842 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4843 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4844 S += '@';
4845 return;
4846 }
4847 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004848 }
Anders Carlssond8499822007-10-29 05:01:08 +00004849 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004850 getLegacyIntegralTypeEncoding(PointeeTy);
4851
Mike Stump11289f42009-09-09 15:08:12 +00004852 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004853 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004854 return;
4855 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004856
Chris Lattnere7cabb92009-07-13 00:10:46 +00004857 if (const ArrayType *AT =
4858 // Ignore type qualifiers etc.
4859 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004860 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004861 // Incomplete arrays are encoded as a pointer to the array element.
4862 S += '^';
4863
Mike Stump11289f42009-09-09 15:08:12 +00004864 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004865 false, ExpandStructures, FD);
4866 } else {
4867 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004868
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004869 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4870 if (getTypeSize(CAT->getElementType()) == 0)
4871 S += '0';
4872 else
4873 S += llvm::utostr(CAT->getSize().getZExtValue());
4874 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004875 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004876 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4877 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004878 S += '0';
4879 }
Mike Stump11289f42009-09-09 15:08:12 +00004880
4881 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004882 false, ExpandStructures, FD);
4883 S += ']';
4884 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004885 return;
4886 }
Mike Stump11289f42009-09-09 15:08:12 +00004887
John McCall9dd450b2009-09-21 23:43:11 +00004888 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004889 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004890 return;
4891 }
Mike Stump11289f42009-09-09 15:08:12 +00004892
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004893 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004894 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004895 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004896 // Anonymous structures print as '?'
4897 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4898 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004899 if (ClassTemplateSpecializationDecl *Spec
4900 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4901 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4902 std::string TemplateArgsStr
4903 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004904 TemplateArgs.data(),
4905 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004906 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004907
4908 S += TemplateArgsStr;
4909 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004910 } else {
4911 S += '?';
4912 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004913 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004914 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004915 if (!RDecl->isUnion()) {
4916 getObjCEncodingForStructureImpl(RDecl, S, FD);
4917 } else {
4918 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4919 FieldEnd = RDecl->field_end();
4920 Field != FieldEnd; ++Field) {
4921 if (FD) {
4922 S += '"';
4923 S += Field->getNameAsString();
4924 S += '"';
4925 }
Mike Stump11289f42009-09-09 15:08:12 +00004926
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004927 // Special case bit-fields.
4928 if (Field->isBitField()) {
4929 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004930 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004931 } else {
4932 QualType qt = Field->getType();
4933 getLegacyIntegralTypeEncoding(qt);
4934 getObjCEncodingForTypeImpl(qt, S, false, true,
4935 FD, /*OutermostType*/false,
4936 /*EncodingProperty*/false,
4937 /*StructField*/true);
4938 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004939 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004940 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004941 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004942 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004943 return;
4944 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004945
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004946 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004947 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004948 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004949 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004950 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004951 return;
4952 }
Mike Stump11289f42009-09-09 15:08:12 +00004953
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004954 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004955 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004956 if (EncodeBlockParameters) {
4957 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4958
4959 S += '<';
4960 // Block return type
4961 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4962 ExpandPointedToStructures, ExpandStructures,
4963 FD,
4964 false /* OutermostType */,
4965 EncodingProperty,
4966 false /* StructField */,
4967 EncodeBlockParameters,
4968 EncodeClassNames);
4969 // Block self
4970 S += "@?";
4971 // Block parameters
4972 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4973 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4974 E = FPT->arg_type_end(); I && (I != E); ++I) {
4975 getObjCEncodingForTypeImpl(*I, S,
4976 ExpandPointedToStructures,
4977 ExpandStructures,
4978 FD,
4979 false /* OutermostType */,
4980 EncodingProperty,
4981 false /* StructField */,
4982 EncodeBlockParameters,
4983 EncodeClassNames);
4984 }
4985 }
4986 S += '>';
4987 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004988 return;
4989 }
Mike Stump11289f42009-09-09 15:08:12 +00004990
John McCall8b07ec22010-05-15 11:32:37 +00004991 // Ignore protocol qualifiers when mangling at this level.
4992 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4993 T = OT->getBaseType();
4994
John McCall8ccfcb52009-09-24 19:53:00 +00004995 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004996 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004997 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004998 S += '{';
4999 const IdentifierInfo *II = OI->getIdentifier();
5000 S += II->getName();
5001 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005002 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005003 DeepCollectObjCIvars(OI, true, Ivars);
5004 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005005 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005006 if (Field->isBitField())
5007 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005008 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005009 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005010 }
5011 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005012 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005013 }
Mike Stump11289f42009-09-09 15:08:12 +00005014
John McCall9dd450b2009-09-21 23:43:11 +00005015 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005016 if (OPT->isObjCIdType()) {
5017 S += '@';
5018 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005019 }
Mike Stump11289f42009-09-09 15:08:12 +00005020
Steve Narofff0c86112009-10-28 22:03:49 +00005021 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5022 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5023 // Since this is a binary compatibility issue, need to consult with runtime
5024 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005025 S += '#';
5026 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005027 }
Mike Stump11289f42009-09-09 15:08:12 +00005028
Chris Lattnere7cabb92009-07-13 00:10:46 +00005029 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005030 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005031 ExpandPointedToStructures,
5032 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005033 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005034 // Note that we do extended encoding of protocol qualifer list
5035 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005036 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005037 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5038 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005039 S += '<';
5040 S += (*I)->getNameAsString();
5041 S += '>';
5042 }
5043 S += '"';
5044 }
5045 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005046 }
Mike Stump11289f42009-09-09 15:08:12 +00005047
Chris Lattnere7cabb92009-07-13 00:10:46 +00005048 QualType PointeeTy = OPT->getPointeeType();
5049 if (!EncodingProperty &&
5050 isa<TypedefType>(PointeeTy.getTypePtr())) {
5051 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005052 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005053 // {...};
5054 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005055 getObjCEncodingForTypeImpl(PointeeTy, S,
5056 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005057 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005058 return;
5059 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005060
5061 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005062 if (OPT->getInterfaceDecl() &&
5063 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005064 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005065 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005066 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5067 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005068 S += '<';
5069 S += (*I)->getNameAsString();
5070 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005071 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005072 S += '"';
5073 }
5074 return;
5075 }
Mike Stump11289f42009-09-09 15:08:12 +00005076
John McCalla9e6e8d2010-05-17 23:56:34 +00005077 // gcc just blithely ignores member pointers.
5078 // TODO: maybe there should be a mangling for these
5079 if (T->getAs<MemberPointerType>())
5080 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005081
5082 if (T->isVectorType()) {
5083 // This matches gcc's encoding, even though technically it is
5084 // insufficient.
5085 // FIXME. We should do a better job than gcc.
5086 return;
5087 }
5088
David Blaikie83d382b2011-09-23 05:06:16 +00005089 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00005090}
5091
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005092void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5093 std::string &S,
5094 const FieldDecl *FD,
5095 bool includeVBases) const {
5096 assert(RDecl && "Expected non-null RecordDecl");
5097 assert(!RDecl->isUnion() && "Should not be called for unions");
5098 if (!RDecl->getDefinition())
5099 return;
5100
5101 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5102 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5103 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5104
5105 if (CXXRec) {
5106 for (CXXRecordDecl::base_class_iterator
5107 BI = CXXRec->bases_begin(),
5108 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5109 if (!BI->isVirtual()) {
5110 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005111 if (base->isEmpty())
5112 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005113 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005114 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5115 std::make_pair(offs, base));
5116 }
5117 }
5118 }
5119
5120 unsigned i = 0;
5121 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5122 FieldEnd = RDecl->field_end();
5123 Field != FieldEnd; ++Field, ++i) {
5124 uint64_t offs = layout.getFieldOffset(i);
5125 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005126 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005127 }
5128
5129 if (CXXRec && includeVBases) {
5130 for (CXXRecordDecl::base_class_iterator
5131 BI = CXXRec->vbases_begin(),
5132 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5133 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005134 if (base->isEmpty())
5135 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005136 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005137 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5138 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5139 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005140 }
5141 }
5142
5143 CharUnits size;
5144 if (CXXRec) {
5145 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5146 } else {
5147 size = layout.getSize();
5148 }
5149
5150 uint64_t CurOffs = 0;
5151 std::multimap<uint64_t, NamedDecl *>::iterator
5152 CurLayObj = FieldOrBaseOffsets.begin();
5153
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005154 if (CXXRec && CXXRec->isDynamicClass() &&
5155 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005156 if (FD) {
5157 S += "\"_vptr$";
5158 std::string recname = CXXRec->getNameAsString();
5159 if (recname.empty()) recname = "?";
5160 S += recname;
5161 S += '"';
5162 }
5163 S += "^^?";
5164 CurOffs += getTypeSize(VoidPtrTy);
5165 }
5166
5167 if (!RDecl->hasFlexibleArrayMember()) {
5168 // Mark the end of the structure.
5169 uint64_t offs = toBits(size);
5170 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5171 std::make_pair(offs, (NamedDecl*)0));
5172 }
5173
5174 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5175 assert(CurOffs <= CurLayObj->first);
5176
5177 if (CurOffs < CurLayObj->first) {
5178 uint64_t padding = CurLayObj->first - CurOffs;
5179 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5180 // packing/alignment of members is different that normal, in which case
5181 // the encoding will be out-of-sync with the real layout.
5182 // If the runtime switches to just consider the size of types without
5183 // taking into account alignment, we could make padding explicit in the
5184 // encoding (e.g. using arrays of chars). The encoding strings would be
5185 // longer then though.
5186 CurOffs += padding;
5187 }
5188
5189 NamedDecl *dcl = CurLayObj->second;
5190 if (dcl == 0)
5191 break; // reached end of structure.
5192
5193 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5194 // We expand the bases without their virtual bases since those are going
5195 // in the initial structure. Note that this differs from gcc which
5196 // expands virtual bases each time one is encountered in the hierarchy,
5197 // making the encoding type bigger than it really is.
5198 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005199 assert(!base->isEmpty());
5200 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005201 } else {
5202 FieldDecl *field = cast<FieldDecl>(dcl);
5203 if (FD) {
5204 S += '"';
5205 S += field->getNameAsString();
5206 S += '"';
5207 }
5208
5209 if (field->isBitField()) {
5210 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005211 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005212 } else {
5213 QualType qt = field->getType();
5214 getLegacyIntegralTypeEncoding(qt);
5215 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5216 /*OutermostType*/false,
5217 /*EncodingProperty*/false,
5218 /*StructField*/true);
5219 CurOffs += getTypeSize(field->getType());
5220 }
5221 }
5222 }
5223}
5224
Mike Stump11289f42009-09-09 15:08:12 +00005225void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005226 std::string& S) const {
5227 if (QT & Decl::OBJC_TQ_In)
5228 S += 'n';
5229 if (QT & Decl::OBJC_TQ_Inout)
5230 S += 'N';
5231 if (QT & Decl::OBJC_TQ_Out)
5232 S += 'o';
5233 if (QT & Decl::OBJC_TQ_Bycopy)
5234 S += 'O';
5235 if (QT & Decl::OBJC_TQ_Byref)
5236 S += 'R';
5237 if (QT & Decl::OBJC_TQ_Oneway)
5238 S += 'V';
5239}
5240
Douglas Gregor3ea72692011-08-12 05:46:01 +00005241TypedefDecl *ASTContext::getObjCIdDecl() const {
5242 if (!ObjCIdDecl) {
5243 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5244 T = getObjCObjectPointerType(T);
5245 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5246 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5247 getTranslationUnitDecl(),
5248 SourceLocation(), SourceLocation(),
5249 &Idents.get("id"), IdInfo);
5250 }
5251
5252 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005253}
5254
Douglas Gregor52e02802011-08-12 06:17:30 +00005255TypedefDecl *ASTContext::getObjCSelDecl() const {
5256 if (!ObjCSelDecl) {
5257 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5258 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5259 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5260 getTranslationUnitDecl(),
5261 SourceLocation(), SourceLocation(),
5262 &Idents.get("SEL"), SelInfo);
5263 }
5264 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005265}
5266
Douglas Gregor0a586182011-08-12 05:59:41 +00005267TypedefDecl *ASTContext::getObjCClassDecl() const {
5268 if (!ObjCClassDecl) {
5269 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5270 T = getObjCObjectPointerType(T);
5271 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5272 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5273 getTranslationUnitDecl(),
5274 SourceLocation(), SourceLocation(),
5275 &Idents.get("Class"), ClassInfo);
5276 }
5277
5278 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005279}
5280
Douglas Gregord53ae832012-01-17 18:09:05 +00005281ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5282 if (!ObjCProtocolClassDecl) {
5283 ObjCProtocolClassDecl
5284 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5285 SourceLocation(),
5286 &Idents.get("Protocol"),
5287 /*PrevDecl=*/0,
5288 SourceLocation(), true);
5289 }
5290
5291 return ObjCProtocolClassDecl;
5292}
5293
Meador Inge5d3fb222012-06-16 03:34:49 +00005294//===----------------------------------------------------------------------===//
5295// __builtin_va_list Construction Functions
5296//===----------------------------------------------------------------------===//
5297
5298static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5299 // typedef char* __builtin_va_list;
5300 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5301 TypeSourceInfo *TInfo
5302 = Context->getTrivialTypeSourceInfo(CharPtrType);
5303
5304 TypedefDecl *VaListTypeDecl
5305 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5306 Context->getTranslationUnitDecl(),
5307 SourceLocation(), SourceLocation(),
5308 &Context->Idents.get("__builtin_va_list"),
5309 TInfo);
5310 return VaListTypeDecl;
5311}
5312
5313static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5314 // typedef void* __builtin_va_list;
5315 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5316 TypeSourceInfo *TInfo
5317 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5318
5319 TypedefDecl *VaListTypeDecl
5320 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5321 Context->getTranslationUnitDecl(),
5322 SourceLocation(), SourceLocation(),
5323 &Context->Idents.get("__builtin_va_list"),
5324 TInfo);
5325 return VaListTypeDecl;
5326}
5327
5328static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5329 // typedef struct __va_list_tag {
5330 RecordDecl *VaListTagDecl;
5331
5332 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5333 Context->getTranslationUnitDecl(),
5334 &Context->Idents.get("__va_list_tag"));
5335 VaListTagDecl->startDefinition();
5336
5337 const size_t NumFields = 5;
5338 QualType FieldTypes[NumFields];
5339 const char *FieldNames[NumFields];
5340
5341 // unsigned char gpr;
5342 FieldTypes[0] = Context->UnsignedCharTy;
5343 FieldNames[0] = "gpr";
5344
5345 // unsigned char fpr;
5346 FieldTypes[1] = Context->UnsignedCharTy;
5347 FieldNames[1] = "fpr";
5348
5349 // unsigned short reserved;
5350 FieldTypes[2] = Context->UnsignedShortTy;
5351 FieldNames[2] = "reserved";
5352
5353 // void* overflow_arg_area;
5354 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5355 FieldNames[3] = "overflow_arg_area";
5356
5357 // void* reg_save_area;
5358 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5359 FieldNames[4] = "reg_save_area";
5360
5361 // Create fields
5362 for (unsigned i = 0; i < NumFields; ++i) {
5363 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5364 SourceLocation(),
5365 SourceLocation(),
5366 &Context->Idents.get(FieldNames[i]),
5367 FieldTypes[i], /*TInfo=*/0,
5368 /*BitWidth=*/0,
5369 /*Mutable=*/false,
5370 ICIS_NoInit);
5371 Field->setAccess(AS_public);
5372 VaListTagDecl->addDecl(Field);
5373 }
5374 VaListTagDecl->completeDefinition();
5375 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005376 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005377
5378 // } __va_list_tag;
5379 TypedefDecl *VaListTagTypedefDecl
5380 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5381 Context->getTranslationUnitDecl(),
5382 SourceLocation(), SourceLocation(),
5383 &Context->Idents.get("__va_list_tag"),
5384 Context->getTrivialTypeSourceInfo(VaListTagType));
5385 QualType VaListTagTypedefType =
5386 Context->getTypedefType(VaListTagTypedefDecl);
5387
5388 // typedef __va_list_tag __builtin_va_list[1];
5389 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5390 QualType VaListTagArrayType
5391 = Context->getConstantArrayType(VaListTagTypedefType,
5392 Size, ArrayType::Normal, 0);
5393 TypeSourceInfo *TInfo
5394 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5395 TypedefDecl *VaListTypedefDecl
5396 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5397 Context->getTranslationUnitDecl(),
5398 SourceLocation(), SourceLocation(),
5399 &Context->Idents.get("__builtin_va_list"),
5400 TInfo);
5401
5402 return VaListTypedefDecl;
5403}
5404
5405static TypedefDecl *
5406CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5407 // typedef struct __va_list_tag {
5408 RecordDecl *VaListTagDecl;
5409 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5410 Context->getTranslationUnitDecl(),
5411 &Context->Idents.get("__va_list_tag"));
5412 VaListTagDecl->startDefinition();
5413
5414 const size_t NumFields = 4;
5415 QualType FieldTypes[NumFields];
5416 const char *FieldNames[NumFields];
5417
5418 // unsigned gp_offset;
5419 FieldTypes[0] = Context->UnsignedIntTy;
5420 FieldNames[0] = "gp_offset";
5421
5422 // unsigned fp_offset;
5423 FieldTypes[1] = Context->UnsignedIntTy;
5424 FieldNames[1] = "fp_offset";
5425
5426 // void* overflow_arg_area;
5427 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5428 FieldNames[2] = "overflow_arg_area";
5429
5430 // void* reg_save_area;
5431 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5432 FieldNames[3] = "reg_save_area";
5433
5434 // Create fields
5435 for (unsigned i = 0; i < NumFields; ++i) {
5436 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5437 VaListTagDecl,
5438 SourceLocation(),
5439 SourceLocation(),
5440 &Context->Idents.get(FieldNames[i]),
5441 FieldTypes[i], /*TInfo=*/0,
5442 /*BitWidth=*/0,
5443 /*Mutable=*/false,
5444 ICIS_NoInit);
5445 Field->setAccess(AS_public);
5446 VaListTagDecl->addDecl(Field);
5447 }
5448 VaListTagDecl->completeDefinition();
5449 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005450 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005451
5452 // } __va_list_tag;
5453 TypedefDecl *VaListTagTypedefDecl
5454 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5455 Context->getTranslationUnitDecl(),
5456 SourceLocation(), SourceLocation(),
5457 &Context->Idents.get("__va_list_tag"),
5458 Context->getTrivialTypeSourceInfo(VaListTagType));
5459 QualType VaListTagTypedefType =
5460 Context->getTypedefType(VaListTagTypedefDecl);
5461
5462 // typedef __va_list_tag __builtin_va_list[1];
5463 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5464 QualType VaListTagArrayType
5465 = Context->getConstantArrayType(VaListTagTypedefType,
5466 Size, ArrayType::Normal,0);
5467 TypeSourceInfo *TInfo
5468 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5469 TypedefDecl *VaListTypedefDecl
5470 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5471 Context->getTranslationUnitDecl(),
5472 SourceLocation(), SourceLocation(),
5473 &Context->Idents.get("__builtin_va_list"),
5474 TInfo);
5475
5476 return VaListTypedefDecl;
5477}
5478
5479static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5480 // typedef int __builtin_va_list[4];
5481 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5482 QualType IntArrayType
5483 = Context->getConstantArrayType(Context->IntTy,
5484 Size, ArrayType::Normal, 0);
5485 TypedefDecl *VaListTypedefDecl
5486 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5487 Context->getTranslationUnitDecl(),
5488 SourceLocation(), SourceLocation(),
5489 &Context->Idents.get("__builtin_va_list"),
5490 Context->getTrivialTypeSourceInfo(IntArrayType));
5491
5492 return VaListTypedefDecl;
5493}
5494
5495static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5496 TargetInfo::BuiltinVaListKind Kind) {
5497 switch (Kind) {
5498 case TargetInfo::CharPtrBuiltinVaList:
5499 return CreateCharPtrBuiltinVaListDecl(Context);
5500 case TargetInfo::VoidPtrBuiltinVaList:
5501 return CreateVoidPtrBuiltinVaListDecl(Context);
5502 case TargetInfo::PowerABIBuiltinVaList:
5503 return CreatePowerABIBuiltinVaListDecl(Context);
5504 case TargetInfo::X86_64ABIBuiltinVaList:
5505 return CreateX86_64ABIBuiltinVaListDecl(Context);
5506 case TargetInfo::PNaClABIBuiltinVaList:
5507 return CreatePNaClABIBuiltinVaListDecl(Context);
5508 }
5509
5510 llvm_unreachable("Unhandled __builtin_va_list type kind");
5511}
5512
5513TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5514 if (!BuiltinVaListDecl)
5515 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5516
5517 return BuiltinVaListDecl;
5518}
5519
Meador Ingecfb60902012-07-01 15:57:25 +00005520QualType ASTContext::getVaListTagType() const {
5521 // Force the creation of VaListTagTy by building the __builtin_va_list
5522 // declaration.
5523 if (VaListTagTy.isNull())
5524 (void) getBuiltinVaListDecl();
5525
5526 return VaListTagTy;
5527}
5528
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005529void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005530 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005531 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005532
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005533 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005534}
5535
John McCalld28ae272009-12-02 08:04:21 +00005536/// \brief Retrieve the template name that corresponds to a non-empty
5537/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005538TemplateName
5539ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5540 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005541 unsigned size = End - Begin;
5542 assert(size > 1 && "set is not overloaded!");
5543
5544 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5545 size * sizeof(FunctionTemplateDecl*));
5546 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5547
5548 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005549 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005550 NamedDecl *D = *I;
5551 assert(isa<FunctionTemplateDecl>(D) ||
5552 (isa<UsingShadowDecl>(D) &&
5553 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5554 *Storage++ = D;
5555 }
5556
5557 return TemplateName(OT);
5558}
5559
Douglas Gregordc572a32009-03-30 22:58:21 +00005560/// \brief Retrieve the template name that represents a qualified
5561/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005562TemplateName
5563ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5564 bool TemplateKeyword,
5565 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005566 assert(NNS && "Missing nested-name-specifier in qualified template name");
5567
Douglas Gregorc42075a2010-02-04 18:10:26 +00005568 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005569 llvm::FoldingSetNodeID ID;
5570 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5571
5572 void *InsertPos = 0;
5573 QualifiedTemplateName *QTN =
5574 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5575 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005576 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5577 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005578 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5579 }
5580
5581 return TemplateName(QTN);
5582}
5583
5584/// \brief Retrieve the template name that represents a dependent
5585/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005586TemplateName
5587ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5588 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005589 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005590 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005591
5592 llvm::FoldingSetNodeID ID;
5593 DependentTemplateName::Profile(ID, NNS, Name);
5594
5595 void *InsertPos = 0;
5596 DependentTemplateName *QTN =
5597 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5598
5599 if (QTN)
5600 return TemplateName(QTN);
5601
5602 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5603 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005604 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5605 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005606 } else {
5607 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005608 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5609 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005610 DependentTemplateName *CheckQTN =
5611 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5612 assert(!CheckQTN && "Dependent type name canonicalization broken");
5613 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005614 }
5615
5616 DependentTemplateNames.InsertNode(QTN, InsertPos);
5617 return TemplateName(QTN);
5618}
5619
Douglas Gregor71395fa2009-11-04 00:56:37 +00005620/// \brief Retrieve the template name that represents a dependent
5621/// template name such as \c MetaFun::template operator+.
5622TemplateName
5623ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005624 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005625 assert((!NNS || NNS->isDependent()) &&
5626 "Nested name specifier must be dependent");
5627
5628 llvm::FoldingSetNodeID ID;
5629 DependentTemplateName::Profile(ID, NNS, Operator);
5630
5631 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005632 DependentTemplateName *QTN
5633 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005634
5635 if (QTN)
5636 return TemplateName(QTN);
5637
5638 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5639 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005640 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5641 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005642 } else {
5643 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00005644 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5645 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005646
5647 DependentTemplateName *CheckQTN
5648 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5649 assert(!CheckQTN && "Dependent template name canonicalization broken");
5650 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005651 }
5652
5653 DependentTemplateNames.InsertNode(QTN, InsertPos);
5654 return TemplateName(QTN);
5655}
5656
Douglas Gregor5590be02011-01-15 06:45:20 +00005657TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005658ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5659 TemplateName replacement) const {
5660 llvm::FoldingSetNodeID ID;
5661 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5662
5663 void *insertPos = 0;
5664 SubstTemplateTemplateParmStorage *subst
5665 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5666
5667 if (!subst) {
5668 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5669 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5670 }
5671
5672 return TemplateName(subst);
5673}
5674
5675TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005676ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5677 const TemplateArgument &ArgPack) const {
5678 ASTContext &Self = const_cast<ASTContext &>(*this);
5679 llvm::FoldingSetNodeID ID;
5680 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5681
5682 void *InsertPos = 0;
5683 SubstTemplateTemplateParmPackStorage *Subst
5684 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5685
5686 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005687 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005688 ArgPack.pack_size(),
5689 ArgPack.pack_begin());
5690 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5691 }
5692
5693 return TemplateName(Subst);
5694}
5695
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005696/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005697/// TargetInfo, produce the corresponding type. The unsigned @p Type
5698/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005699CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005700 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005701 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005702 case TargetInfo::SignedShort: return ShortTy;
5703 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5704 case TargetInfo::SignedInt: return IntTy;
5705 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5706 case TargetInfo::SignedLong: return LongTy;
5707 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5708 case TargetInfo::SignedLongLong: return LongLongTy;
5709 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5710 }
5711
David Blaikie83d382b2011-09-23 05:06:16 +00005712 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005713}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005714
5715//===----------------------------------------------------------------------===//
5716// Type Predicates.
5717//===----------------------------------------------------------------------===//
5718
Fariborz Jahanian96207692009-02-18 21:49:28 +00005719/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5720/// garbage collection attribute.
5721///
John McCall553d45a2011-01-12 00:34:59 +00005722Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005723 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005724 return Qualifiers::GCNone;
5725
David Blaikiebbafb8a2012-03-11 07:00:24 +00005726 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005727 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5728
5729 // Default behaviour under objective-C's gc is for ObjC pointers
5730 // (or pointers to them) be treated as though they were declared
5731 // as __strong.
5732 if (GCAttrs == Qualifiers::GCNone) {
5733 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5734 return Qualifiers::Strong;
5735 else if (Ty->isPointerType())
5736 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5737 } else {
5738 // It's not valid to set GC attributes on anything that isn't a
5739 // pointer.
5740#ifndef NDEBUG
5741 QualType CT = Ty->getCanonicalTypeInternal();
5742 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5743 CT = AT->getElementType();
5744 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5745#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005746 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005747 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005748}
5749
Chris Lattner49af6a42008-04-07 06:51:04 +00005750//===----------------------------------------------------------------------===//
5751// Type Compatibility Testing
5752//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005753
Mike Stump11289f42009-09-09 15:08:12 +00005754/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005755/// compatible.
5756static bool areCompatVectorTypes(const VectorType *LHS,
5757 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005758 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005759 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005760 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005761}
5762
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005763bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5764 QualType SecondVec) {
5765 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5766 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5767
5768 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5769 return true;
5770
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005771 // Treat Neon vector types and most AltiVec vector types as if they are the
5772 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005773 const VectorType *First = FirstVec->getAs<VectorType>();
5774 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005775 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005776 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005777 First->getVectorKind() != VectorType::AltiVecPixel &&
5778 First->getVectorKind() != VectorType::AltiVecBool &&
5779 Second->getVectorKind() != VectorType::AltiVecPixel &&
5780 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005781 return true;
5782
5783 return false;
5784}
5785
Steve Naroff8e6aee52009-07-23 01:01:38 +00005786//===----------------------------------------------------------------------===//
5787// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5788//===----------------------------------------------------------------------===//
5789
5790/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5791/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005792bool
5793ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5794 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005795 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005796 return true;
5797 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5798 E = rProto->protocol_end(); PI != E; ++PI)
5799 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5800 return true;
5801 return false;
5802}
5803
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005804/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00005805/// return true if lhs's protocols conform to rhs's protocol; false
5806/// otherwise.
5807bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5808 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5809 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5810 return false;
5811}
5812
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00005813/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
5814/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005815bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5816 QualType rhs) {
5817 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5818 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5819 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5820
5821 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5822 E = lhsQID->qual_end(); I != E; ++I) {
5823 bool match = false;
5824 ObjCProtocolDecl *lhsProto = *I;
5825 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5826 E = rhsOPT->qual_end(); J != E; ++J) {
5827 ObjCProtocolDecl *rhsProto = *J;
5828 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5829 match = true;
5830 break;
5831 }
5832 }
5833 if (!match)
5834 return false;
5835 }
5836 return true;
5837}
5838
Steve Naroff8e6aee52009-07-23 01:01:38 +00005839/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5840/// ObjCQualifiedIDType.
5841bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5842 bool compare) {
5843 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005844 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005845 lhs->isObjCIdType() || lhs->isObjCClassType())
5846 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005847 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005848 rhs->isObjCIdType() || rhs->isObjCClassType())
5849 return true;
5850
5851 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005852 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005853
Steve Naroff8e6aee52009-07-23 01:01:38 +00005854 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005855
Steve Naroff8e6aee52009-07-23 01:01:38 +00005856 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005857 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005858 // make sure we check the class hierarchy.
5859 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5860 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5861 E = lhsQID->qual_end(); I != E; ++I) {
5862 // when comparing an id<P> on lhs with a static type on rhs,
5863 // see if static class implements all of id's protocols, directly or
5864 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005865 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005866 return false;
5867 }
5868 }
5869 // If there are no qualifiers and no interface, we have an 'id'.
5870 return true;
5871 }
Mike Stump11289f42009-09-09 15:08:12 +00005872 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005873 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5874 E = lhsQID->qual_end(); I != E; ++I) {
5875 ObjCProtocolDecl *lhsProto = *I;
5876 bool match = false;
5877
5878 // when comparing an id<P> on lhs with a static type on rhs,
5879 // see if static class implements all of id's protocols, directly or
5880 // through its super class and categories.
5881 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5882 E = rhsOPT->qual_end(); J != E; ++J) {
5883 ObjCProtocolDecl *rhsProto = *J;
5884 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5885 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5886 match = true;
5887 break;
5888 }
5889 }
Mike Stump11289f42009-09-09 15:08:12 +00005890 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005891 // make sure we check the class hierarchy.
5892 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5893 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5894 E = lhsQID->qual_end(); I != E; ++I) {
5895 // when comparing an id<P> on lhs with a static type on rhs,
5896 // see if static class implements all of id's protocols, directly or
5897 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005898 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005899 match = true;
5900 break;
5901 }
5902 }
5903 }
5904 if (!match)
5905 return false;
5906 }
Mike Stump11289f42009-09-09 15:08:12 +00005907
Steve Naroff8e6aee52009-07-23 01:01:38 +00005908 return true;
5909 }
Mike Stump11289f42009-09-09 15:08:12 +00005910
Steve Naroff8e6aee52009-07-23 01:01:38 +00005911 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5912 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5913
Mike Stump11289f42009-09-09 15:08:12 +00005914 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005915 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005916 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005917 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5918 E = lhsOPT->qual_end(); I != E; ++I) {
5919 ObjCProtocolDecl *lhsProto = *I;
5920 bool match = false;
5921
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005922 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005923 // see if static class implements all of id's protocols, directly or
5924 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005925 // First, lhs protocols in the qualifier list must be found, direct
5926 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005927 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5928 E = rhsQID->qual_end(); J != E; ++J) {
5929 ObjCProtocolDecl *rhsProto = *J;
5930 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5931 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5932 match = true;
5933 break;
5934 }
5935 }
5936 if (!match)
5937 return false;
5938 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005939
5940 // Static class's protocols, or its super class or category protocols
5941 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5942 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5943 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5944 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5945 // This is rather dubious but matches gcc's behavior. If lhs has
5946 // no type qualifier and its class has no static protocol(s)
5947 // assume that it is mismatch.
5948 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5949 return false;
5950 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5951 LHSInheritedProtocols.begin(),
5952 E = LHSInheritedProtocols.end(); I != E; ++I) {
5953 bool match = false;
5954 ObjCProtocolDecl *lhsProto = (*I);
5955 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5956 E = rhsQID->qual_end(); J != E; ++J) {
5957 ObjCProtocolDecl *rhsProto = *J;
5958 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5959 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5960 match = true;
5961 break;
5962 }
5963 }
5964 if (!match)
5965 return false;
5966 }
5967 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005968 return true;
5969 }
5970 return false;
5971}
5972
Eli Friedman47f77112008-08-22 00:56:42 +00005973/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005974/// compatible for assignment from RHS to LHS. This handles validation of any
5975/// protocol qualifiers on the LHS or RHS.
5976///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005977bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5978 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005979 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5980 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5981
Steve Naroff1329fa02009-07-15 18:40:39 +00005982 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005983 if (LHS->isObjCUnqualifiedIdOrClass() ||
5984 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005985 return true;
5986
John McCall8b07ec22010-05-15 11:32:37 +00005987 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005988 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5989 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005990 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005991
5992 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5993 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5994 QualType(RHSOPT,0));
5995
John McCall8b07ec22010-05-15 11:32:37 +00005996 // If we have 2 user-defined types, fall into that path.
5997 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005998 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005999
Steve Naroff8e6aee52009-07-23 01:01:38 +00006000 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006001}
6002
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006003/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006004/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006005/// arguments in block literals. When passed as arguments, passing 'A*' where
6006/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6007/// not OK. For the return type, the opposite is not OK.
6008bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6009 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006010 const ObjCObjectPointerType *RHSOPT,
6011 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006012 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006013 return true;
6014
6015 if (LHSOPT->isObjCBuiltinType()) {
6016 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6017 }
6018
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006019 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006020 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6021 QualType(RHSOPT,0),
6022 false);
6023
6024 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6025 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6026 if (LHS && RHS) { // We have 2 user-defined types.
6027 if (LHS != RHS) {
6028 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006029 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006030 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006031 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006032 }
6033 else
6034 return true;
6035 }
6036 return false;
6037}
6038
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006039/// getIntersectionOfProtocols - This routine finds the intersection of set
6040/// of protocols inherited from two distinct objective-c pointer objects.
6041/// It is used to build composite qualifier list of the composite type of
6042/// the conditional expression involving two objective-c pointer objects.
6043static
6044void getIntersectionOfProtocols(ASTContext &Context,
6045 const ObjCObjectPointerType *LHSOPT,
6046 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006047 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006048
John McCall8b07ec22010-05-15 11:32:37 +00006049 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6050 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6051 assert(LHS->getInterface() && "LHS must have an interface base");
6052 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006053
6054 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6055 unsigned LHSNumProtocols = LHS->getNumProtocols();
6056 if (LHSNumProtocols > 0)
6057 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6058 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006059 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006060 Context.CollectInheritedProtocols(LHS->getInterface(),
6061 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006062 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6063 LHSInheritedProtocols.end());
6064 }
6065
6066 unsigned RHSNumProtocols = RHS->getNumProtocols();
6067 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006068 ObjCProtocolDecl **RHSProtocols =
6069 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006070 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6071 if (InheritedProtocolSet.count(RHSProtocols[i]))
6072 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006073 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006074 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006075 Context.CollectInheritedProtocols(RHS->getInterface(),
6076 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006077 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6078 RHSInheritedProtocols.begin(),
6079 E = RHSInheritedProtocols.end(); I != E; ++I)
6080 if (InheritedProtocolSet.count((*I)))
6081 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006082 }
6083}
6084
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006085/// areCommonBaseCompatible - Returns common base class of the two classes if
6086/// one found. Note that this is O'2 algorithm. But it will be called as the
6087/// last type comparison in a ?-exp of ObjC pointer types before a
6088/// warning is issued. So, its invokation is extremely rare.
6089QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006090 const ObjCObjectPointerType *Lptr,
6091 const ObjCObjectPointerType *Rptr) {
6092 const ObjCObjectType *LHS = Lptr->getObjectType();
6093 const ObjCObjectType *RHS = Rptr->getObjectType();
6094 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6095 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006096 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006097 return QualType();
6098
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006099 do {
John McCall8b07ec22010-05-15 11:32:37 +00006100 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006101 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006102 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006103 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6104
6105 QualType Result = QualType(LHS, 0);
6106 if (!Protocols.empty())
6107 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6108 Result = getObjCObjectPointerType(Result);
6109 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006110 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006111 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006112
6113 return QualType();
6114}
6115
John McCall8b07ec22010-05-15 11:32:37 +00006116bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6117 const ObjCObjectType *RHS) {
6118 assert(LHS->getInterface() && "LHS is not an interface type");
6119 assert(RHS->getInterface() && "RHS is not an interface type");
6120
Chris Lattner49af6a42008-04-07 06:51:04 +00006121 // Verify that the base decls are compatible: the RHS must be a subclass of
6122 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006123 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006124 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006125
Chris Lattner49af6a42008-04-07 06:51:04 +00006126 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6127 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006128 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006129 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006130
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006131 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6132 // more detailed analysis is required.
6133 if (RHS->getNumProtocols() == 0) {
6134 // OK, if LHS is a superclass of RHS *and*
6135 // this superclass is assignment compatible with LHS.
6136 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006137 bool IsSuperClass =
6138 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6139 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006140 // OK if conversion of LHS to SuperClass results in narrowing of types
6141 // ; i.e., SuperClass may implement at least one of the protocols
6142 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6143 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6144 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006145 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006146 // If super class has no protocols, it is not a match.
6147 if (SuperClassInheritedProtocols.empty())
6148 return false;
6149
6150 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6151 LHSPE = LHS->qual_end();
6152 LHSPI != LHSPE; LHSPI++) {
6153 bool SuperImplementsProtocol = false;
6154 ObjCProtocolDecl *LHSProto = (*LHSPI);
6155
6156 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6157 SuperClassInheritedProtocols.begin(),
6158 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6159 ObjCProtocolDecl *SuperClassProto = (*I);
6160 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6161 SuperImplementsProtocol = true;
6162 break;
6163 }
6164 }
6165 if (!SuperImplementsProtocol)
6166 return false;
6167 }
6168 return true;
6169 }
6170 return false;
6171 }
Mike Stump11289f42009-09-09 15:08:12 +00006172
John McCall8b07ec22010-05-15 11:32:37 +00006173 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6174 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006175 LHSPI != LHSPE; LHSPI++) {
6176 bool RHSImplementsProtocol = false;
6177
6178 // If the RHS doesn't implement the protocol on the left, the types
6179 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006180 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6181 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006182 RHSPI != RHSPE; RHSPI++) {
6183 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006184 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006185 break;
6186 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006187 }
6188 // FIXME: For better diagnostics, consider passing back the protocol name.
6189 if (!RHSImplementsProtocol)
6190 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006191 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006192 // The RHS implements all protocols listed on the LHS.
6193 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006194}
6195
Steve Naroffb7605152009-02-12 17:52:19 +00006196bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6197 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006198 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6199 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006200
Steve Naroff7cae42b2009-07-10 23:34:53 +00006201 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006202 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006203
6204 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6205 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006206}
6207
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006208bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6209 return canAssignObjCInterfaces(
6210 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6211 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6212}
6213
Mike Stump11289f42009-09-09 15:08:12 +00006214/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006215/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006216/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006217/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006218bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6219 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006220 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006221 return hasSameType(LHS, RHS);
6222
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006223 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006224}
6225
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006226bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006227 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006228}
6229
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006230bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6231 return !mergeTypes(LHS, RHS, true).isNull();
6232}
6233
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006234/// mergeTransparentUnionType - if T is a transparent union type and a member
6235/// of T is compatible with SubType, return the merged type, else return
6236/// QualType()
6237QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6238 bool OfBlockPointer,
6239 bool Unqualified) {
6240 if (const RecordType *UT = T->getAsUnionType()) {
6241 RecordDecl *UD = UT->getDecl();
6242 if (UD->hasAttr<TransparentUnionAttr>()) {
6243 for (RecordDecl::field_iterator it = UD->field_begin(),
6244 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006245 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006246 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6247 if (!MT.isNull())
6248 return MT;
6249 }
6250 }
6251 }
6252
6253 return QualType();
6254}
6255
6256/// mergeFunctionArgumentTypes - merge two types which appear as function
6257/// argument types
6258QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6259 bool OfBlockPointer,
6260 bool Unqualified) {
6261 // GNU extension: two types are compatible if they appear as a function
6262 // argument, one of the types is a transparent union type and the other
6263 // type is compatible with a union member
6264 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6265 Unqualified);
6266 if (!lmerge.isNull())
6267 return lmerge;
6268
6269 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6270 Unqualified);
6271 if (!rmerge.isNull())
6272 return rmerge;
6273
6274 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6275}
6276
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006277QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006278 bool OfBlockPointer,
6279 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006280 const FunctionType *lbase = lhs->getAs<FunctionType>();
6281 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006282 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6283 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006284 bool allLTypes = true;
6285 bool allRTypes = true;
6286
6287 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006288 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006289 if (OfBlockPointer) {
6290 QualType RHS = rbase->getResultType();
6291 QualType LHS = lbase->getResultType();
6292 bool UnqualifiedResult = Unqualified;
6293 if (!UnqualifiedResult)
6294 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006295 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006296 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006297 else
John McCall8c6b56f2010-12-15 01:06:38 +00006298 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6299 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006300 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006301
6302 if (Unqualified)
6303 retType = retType.getUnqualifiedType();
6304
6305 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6306 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6307 if (Unqualified) {
6308 LRetType = LRetType.getUnqualifiedType();
6309 RRetType = RRetType.getUnqualifiedType();
6310 }
6311
6312 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006313 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006314 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006315 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006316
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006317 // FIXME: double check this
6318 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6319 // rbase->getRegParmAttr() != 0 &&
6320 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006321 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6322 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006323
Douglas Gregor8c940862010-01-18 17:14:39 +00006324 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006325 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006326 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006327
John McCall8c6b56f2010-12-15 01:06:38 +00006328 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006329 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6330 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006331 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6332 return QualType();
6333
John McCall31168b02011-06-15 23:02:42 +00006334 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6335 return QualType();
6336
Fariborz Jahanian48c69102011-10-05 00:05:34 +00006337 // functypes which return are preferred over those that do not.
6338 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6339 allLTypes = false;
6340 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6341 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006342 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6343 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006344
John McCall31168b02011-06-15 23:02:42 +00006345 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006346
Eli Friedman47f77112008-08-22 00:56:42 +00006347 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006348 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6349 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006350 unsigned lproto_nargs = lproto->getNumArgs();
6351 unsigned rproto_nargs = rproto->getNumArgs();
6352
6353 // Compatible functions must have the same number of arguments
6354 if (lproto_nargs != rproto_nargs)
6355 return QualType();
6356
6357 // Variadic and non-variadic functions aren't compatible
6358 if (lproto->isVariadic() != rproto->isVariadic())
6359 return QualType();
6360
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006361 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6362 return QualType();
6363
Fariborz Jahanian97676972011-09-28 21:52:05 +00006364 if (LangOpts.ObjCAutoRefCount &&
6365 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6366 return QualType();
6367
Eli Friedman47f77112008-08-22 00:56:42 +00006368 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006369 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006370 for (unsigned i = 0; i < lproto_nargs; i++) {
6371 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6372 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006373 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6374 OfBlockPointer,
6375 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006376 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006377
6378 if (Unqualified)
6379 argtype = argtype.getUnqualifiedType();
6380
Eli Friedman47f77112008-08-22 00:56:42 +00006381 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006382 if (Unqualified) {
6383 largtype = largtype.getUnqualifiedType();
6384 rargtype = rargtype.getUnqualifiedType();
6385 }
6386
Chris Lattner465fa322008-10-05 17:34:18 +00006387 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6388 allLTypes = false;
6389 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6390 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006391 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006392
Eli Friedman47f77112008-08-22 00:56:42 +00006393 if (allLTypes) return lhs;
6394 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006395
6396 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6397 EPI.ExtInfo = einfo;
6398 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006399 }
6400
6401 if (lproto) allRTypes = false;
6402 if (rproto) allLTypes = false;
6403
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006404 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006405 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006406 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006407 if (proto->isVariadic()) return QualType();
6408 // Check that the types are compatible with the types that
6409 // would result from default argument promotions (C99 6.7.5.3p15).
6410 // The only types actually affected are promotable integer
6411 // types and floats, which would be passed as a different
6412 // type depending on whether the prototype is visible.
6413 unsigned proto_nargs = proto->getNumArgs();
6414 for (unsigned i = 0; i < proto_nargs; ++i) {
6415 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006416
Eli Friedman448ce402012-08-30 00:44:15 +00006417 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006418 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006419 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6420 argTy = Enum->getDecl()->getIntegerType();
6421 if (argTy.isNull())
6422 return QualType();
6423 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006424
Eli Friedman47f77112008-08-22 00:56:42 +00006425 if (argTy->isPromotableIntegerType() ||
6426 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6427 return QualType();
6428 }
6429
6430 if (allLTypes) return lhs;
6431 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006432
6433 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6434 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006435 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006436 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006437 }
6438
6439 if (allLTypes) return lhs;
6440 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006441 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006442}
6443
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006444QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006445 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006446 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006447 // C++ [expr]: If an expression initially has the type "reference to T", the
6448 // type is adjusted to "T" prior to any further analysis, the expression
6449 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006450 // expression is an lvalue unless the reference is an rvalue reference and
6451 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006452 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6453 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006454
6455 if (Unqualified) {
6456 LHS = LHS.getUnqualifiedType();
6457 RHS = RHS.getUnqualifiedType();
6458 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006459
Eli Friedman47f77112008-08-22 00:56:42 +00006460 QualType LHSCan = getCanonicalType(LHS),
6461 RHSCan = getCanonicalType(RHS);
6462
6463 // If two types are identical, they are compatible.
6464 if (LHSCan == RHSCan)
6465 return LHS;
6466
John McCall8ccfcb52009-09-24 19:53:00 +00006467 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006468 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6469 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006470 if (LQuals != RQuals) {
6471 // If any of these qualifiers are different, we have a type
6472 // mismatch.
6473 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006474 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6475 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006476 return QualType();
6477
6478 // Exactly one GC qualifier difference is allowed: __strong is
6479 // okay if the other type has no GC qualifier but is an Objective
6480 // C object pointer (i.e. implicitly strong by default). We fix
6481 // this by pretending that the unqualified type was actually
6482 // qualified __strong.
6483 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6484 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6485 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6486
6487 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6488 return QualType();
6489
6490 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6491 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6492 }
6493 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6494 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6495 }
Eli Friedman47f77112008-08-22 00:56:42 +00006496 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006497 }
6498
6499 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006500
Eli Friedmandcca6332009-06-01 01:22:52 +00006501 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6502 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006503
Chris Lattnerfd652912008-01-14 05:45:46 +00006504 // We want to consider the two function types to be the same for these
6505 // comparisons, just force one to the other.
6506 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6507 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006508
6509 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006510 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6511 LHSClass = Type::ConstantArray;
6512 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6513 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006514
John McCall8b07ec22010-05-15 11:32:37 +00006515 // ObjCInterfaces are just specialized ObjCObjects.
6516 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6517 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6518
Nate Begemance4d7fc2008-04-18 23:10:10 +00006519 // Canonicalize ExtVector -> Vector.
6520 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6521 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006522
Chris Lattner95554662008-04-07 05:43:21 +00006523 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006524 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006525 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006526 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006527 // Compatibility is based on the underlying type, not the promotion
6528 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006529 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006530 QualType TINT = ETy->getDecl()->getIntegerType();
6531 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006532 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006533 }
John McCall9dd450b2009-09-21 23:43:11 +00006534 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006535 QualType TINT = ETy->getDecl()->getIntegerType();
6536 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006537 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006538 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006539 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006540 if (OfBlockPointer && !BlockReturnType) {
6541 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6542 return LHS;
6543 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6544 return RHS;
6545 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006546
Eli Friedman47f77112008-08-22 00:56:42 +00006547 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006548 }
Eli Friedman47f77112008-08-22 00:56:42 +00006549
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006550 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006551 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006552#define TYPE(Class, Base)
6553#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006554#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006555#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6556#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6557#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006558 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006559
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006560 case Type::LValueReference:
6561 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006562 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006563 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006564
John McCall8b07ec22010-05-15 11:32:37 +00006565 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006566 case Type::IncompleteArray:
6567 case Type::VariableArray:
6568 case Type::FunctionProto:
6569 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006570 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006571
Chris Lattnerfd652912008-01-14 05:45:46 +00006572 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006573 {
6574 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006575 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6576 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006577 if (Unqualified) {
6578 LHSPointee = LHSPointee.getUnqualifiedType();
6579 RHSPointee = RHSPointee.getUnqualifiedType();
6580 }
6581 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6582 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006583 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006584 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006585 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006586 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006587 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006588 return getPointerType(ResultType);
6589 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006590 case Type::BlockPointer:
6591 {
6592 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006593 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6594 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006595 if (Unqualified) {
6596 LHSPointee = LHSPointee.getUnqualifiedType();
6597 RHSPointee = RHSPointee.getUnqualifiedType();
6598 }
6599 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6600 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006601 if (ResultType.isNull()) return QualType();
6602 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6603 return LHS;
6604 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6605 return RHS;
6606 return getBlockPointerType(ResultType);
6607 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006608 case Type::Atomic:
6609 {
6610 // Merge two pointer types, while trying to preserve typedef info
6611 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6612 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6613 if (Unqualified) {
6614 LHSValue = LHSValue.getUnqualifiedType();
6615 RHSValue = RHSValue.getUnqualifiedType();
6616 }
6617 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6618 Unqualified);
6619 if (ResultType.isNull()) return QualType();
6620 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6621 return LHS;
6622 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6623 return RHS;
6624 return getAtomicType(ResultType);
6625 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006626 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006627 {
6628 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6629 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6630 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6631 return QualType();
6632
6633 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6634 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006635 if (Unqualified) {
6636 LHSElem = LHSElem.getUnqualifiedType();
6637 RHSElem = RHSElem.getUnqualifiedType();
6638 }
6639
6640 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006641 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006642 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6643 return LHS;
6644 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6645 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006646 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6647 ArrayType::ArraySizeModifier(), 0);
6648 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6649 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006650 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6651 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006652 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6653 return LHS;
6654 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6655 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006656 if (LVAT) {
6657 // FIXME: This isn't correct! But tricky to implement because
6658 // the array's size has to be the size of LHS, but the type
6659 // has to be different.
6660 return LHS;
6661 }
6662 if (RVAT) {
6663 // FIXME: This isn't correct! But tricky to implement because
6664 // the array's size has to be the size of RHS, but the type
6665 // has to be different.
6666 return RHS;
6667 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006668 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6669 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006670 return getIncompleteArrayType(ResultType,
6671 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006672 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006673 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006674 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006675 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006676 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006677 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006678 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006679 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006680 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006681 case Type::Complex:
6682 // Distinct complex types are incompatible.
6683 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006684 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006685 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006686 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6687 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006688 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006689 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006690 case Type::ObjCObject: {
6691 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006692 // FIXME: This should be type compatibility, e.g. whether
6693 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006694 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6695 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6696 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006697 return LHS;
6698
Eli Friedman47f77112008-08-22 00:56:42 +00006699 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006700 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006701 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006702 if (OfBlockPointer) {
6703 if (canAssignObjCInterfacesInBlockPointer(
6704 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006705 RHS->getAs<ObjCObjectPointerType>(),
6706 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006707 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006708 return QualType();
6709 }
John McCall9dd450b2009-09-21 23:43:11 +00006710 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6711 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006712 return LHS;
6713
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006714 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006715 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006716 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006717
David Blaikie8a40f702012-01-17 06:56:22 +00006718 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006719}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006720
Fariborz Jahanian97676972011-09-28 21:52:05 +00006721bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6722 const FunctionProtoType *FromFunctionType,
6723 const FunctionProtoType *ToFunctionType) {
6724 if (FromFunctionType->hasAnyConsumedArgs() !=
6725 ToFunctionType->hasAnyConsumedArgs())
6726 return false;
6727 FunctionProtoType::ExtProtoInfo FromEPI =
6728 FromFunctionType->getExtProtoInfo();
6729 FunctionProtoType::ExtProtoInfo ToEPI =
6730 ToFunctionType->getExtProtoInfo();
6731 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6732 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6733 ArgIdx != NumArgs; ++ArgIdx) {
6734 if (FromEPI.ConsumedArguments[ArgIdx] !=
6735 ToEPI.ConsumedArguments[ArgIdx])
6736 return false;
6737 }
6738 return true;
6739}
6740
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006741/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6742/// 'RHS' attributes and returns the merged version; including for function
6743/// return types.
6744QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6745 QualType LHSCan = getCanonicalType(LHS),
6746 RHSCan = getCanonicalType(RHS);
6747 // If two types are identical, they are compatible.
6748 if (LHSCan == RHSCan)
6749 return LHS;
6750 if (RHSCan->isFunctionType()) {
6751 if (!LHSCan->isFunctionType())
6752 return QualType();
6753 QualType OldReturnType =
6754 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6755 QualType NewReturnType =
6756 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6757 QualType ResReturnType =
6758 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6759 if (ResReturnType.isNull())
6760 return QualType();
6761 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6762 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6763 // In either case, use OldReturnType to build the new function type.
6764 const FunctionType *F = LHS->getAs<FunctionType>();
6765 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006766 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6767 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006768 QualType ResultType
6769 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006770 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006771 return ResultType;
6772 }
6773 }
6774 return QualType();
6775 }
6776
6777 // If the qualifiers are different, the types can still be merged.
6778 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6779 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6780 if (LQuals != RQuals) {
6781 // If any of these qualifiers are different, we have a type mismatch.
6782 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6783 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6784 return QualType();
6785
6786 // Exactly one GC qualifier difference is allowed: __strong is
6787 // okay if the other type has no GC qualifier but is an Objective
6788 // C object pointer (i.e. implicitly strong by default). We fix
6789 // this by pretending that the unqualified type was actually
6790 // qualified __strong.
6791 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6792 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6793 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6794
6795 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6796 return QualType();
6797
6798 if (GC_L == Qualifiers::Strong)
6799 return LHS;
6800 if (GC_R == Qualifiers::Strong)
6801 return RHS;
6802 return QualType();
6803 }
6804
6805 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6806 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6807 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6808 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6809 if (ResQT == LHSBaseQT)
6810 return LHS;
6811 if (ResQT == RHSBaseQT)
6812 return RHS;
6813 }
6814 return QualType();
6815}
6816
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006817//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006818// Integer Predicates
6819//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006820
Jay Foad39c79802011-01-12 09:06:06 +00006821unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006822 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006823 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006824 if (T->isBooleanType())
6825 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006826 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006827 return (unsigned)getTypeSize(T);
6828}
6829
6830QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006831 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006832
6833 // Turn <4 x signed int> -> <4 x unsigned int>
6834 if (const VectorType *VTy = T->getAs<VectorType>())
6835 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006836 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006837
6838 // For enums, we return the unsigned version of the base type.
6839 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006840 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006841
6842 const BuiltinType *BTy = T->getAs<BuiltinType>();
6843 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006844 switch (BTy->getKind()) {
6845 case BuiltinType::Char_S:
6846 case BuiltinType::SChar:
6847 return UnsignedCharTy;
6848 case BuiltinType::Short:
6849 return UnsignedShortTy;
6850 case BuiltinType::Int:
6851 return UnsignedIntTy;
6852 case BuiltinType::Long:
6853 return UnsignedLongTy;
6854 case BuiltinType::LongLong:
6855 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006856 case BuiltinType::Int128:
6857 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006858 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006859 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006860 }
6861}
6862
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006863ASTMutationListener::~ASTMutationListener() { }
6864
Chris Lattnerecd79c62009-06-14 00:45:47 +00006865
6866//===----------------------------------------------------------------------===//
6867// Builtin Type Computation
6868//===----------------------------------------------------------------------===//
6869
6870/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006871/// pointer over the consumed characters. This returns the resultant type. If
6872/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6873/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6874/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006875///
6876/// RequiresICE is filled in on return to indicate whether the value is required
6877/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006878static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006879 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006880 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006881 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006882 // Modifiers.
6883 int HowLong = 0;
6884 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006885 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006886
Chris Lattnerdc226c22010-10-01 22:42:38 +00006887 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006888 bool Done = false;
6889 while (!Done) {
6890 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006891 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006892 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006893 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006894 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006895 case 'S':
6896 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6897 assert(!Signed && "Can't use 'S' modifier multiple times!");
6898 Signed = true;
6899 break;
6900 case 'U':
6901 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6902 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6903 Unsigned = true;
6904 break;
6905 case 'L':
6906 assert(HowLong <= 2 && "Can't have LLLL modifier");
6907 ++HowLong;
6908 break;
6909 }
6910 }
6911
6912 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006913
Chris Lattnerecd79c62009-06-14 00:45:47 +00006914 // Read the base type.
6915 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006916 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006917 case 'v':
6918 assert(HowLong == 0 && !Signed && !Unsigned &&
6919 "Bad modifiers used with 'v'!");
6920 Type = Context.VoidTy;
6921 break;
6922 case 'f':
6923 assert(HowLong == 0 && !Signed && !Unsigned &&
6924 "Bad modifiers used with 'f'!");
6925 Type = Context.FloatTy;
6926 break;
6927 case 'd':
6928 assert(HowLong < 2 && !Signed && !Unsigned &&
6929 "Bad modifiers used with 'd'!");
6930 if (HowLong)
6931 Type = Context.LongDoubleTy;
6932 else
6933 Type = Context.DoubleTy;
6934 break;
6935 case 's':
6936 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6937 if (Unsigned)
6938 Type = Context.UnsignedShortTy;
6939 else
6940 Type = Context.ShortTy;
6941 break;
6942 case 'i':
6943 if (HowLong == 3)
6944 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6945 else if (HowLong == 2)
6946 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6947 else if (HowLong == 1)
6948 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6949 else
6950 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6951 break;
6952 case 'c':
6953 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6954 if (Signed)
6955 Type = Context.SignedCharTy;
6956 else if (Unsigned)
6957 Type = Context.UnsignedCharTy;
6958 else
6959 Type = Context.CharTy;
6960 break;
6961 case 'b': // boolean
6962 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6963 Type = Context.BoolTy;
6964 break;
6965 case 'z': // size_t.
6966 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6967 Type = Context.getSizeType();
6968 break;
6969 case 'F':
6970 Type = Context.getCFConstantStringType();
6971 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006972 case 'G':
6973 Type = Context.getObjCIdType();
6974 break;
6975 case 'H':
6976 Type = Context.getObjCSelType();
6977 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006978 case 'a':
6979 Type = Context.getBuiltinVaListType();
6980 assert(!Type.isNull() && "builtin va list type not initialized!");
6981 break;
6982 case 'A':
6983 // This is a "reference" to a va_list; however, what exactly
6984 // this means depends on how va_list is defined. There are two
6985 // different kinds of va_list: ones passed by value, and ones
6986 // passed by reference. An example of a by-value va_list is
6987 // x86, where va_list is a char*. An example of by-ref va_list
6988 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6989 // we want this argument to be a char*&; for x86-64, we want
6990 // it to be a __va_list_tag*.
6991 Type = Context.getBuiltinVaListType();
6992 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006993 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006994 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006995 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006996 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006997 break;
6998 case 'V': {
6999 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007000 unsigned NumElements = strtoul(Str, &End, 10);
7001 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007002 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007003
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007004 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7005 RequiresICE, false);
7006 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007007
7008 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007009 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007010 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007011 break;
7012 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007013 case 'E': {
7014 char *End;
7015
7016 unsigned NumElements = strtoul(Str, &End, 10);
7017 assert(End != Str && "Missing vector size");
7018
7019 Str = End;
7020
7021 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7022 false);
7023 Type = Context.getExtVectorType(ElementType, NumElements);
7024 break;
7025 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007026 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007027 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7028 false);
7029 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007030 Type = Context.getComplexType(ElementType);
7031 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007032 }
7033 case 'Y' : {
7034 Type = Context.getPointerDiffType();
7035 break;
7036 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007037 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007038 Type = Context.getFILEType();
7039 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007040 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007041 return QualType();
7042 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007043 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007044 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007045 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007046 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007047 else
7048 Type = Context.getjmp_bufType();
7049
Mike Stump2adb4da2009-07-28 23:47:15 +00007050 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007051 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007052 return QualType();
7053 }
7054 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007055 case 'K':
7056 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7057 Type = Context.getucontext_tType();
7058
7059 if (Type.isNull()) {
7060 Error = ASTContext::GE_Missing_ucontext;
7061 return QualType();
7062 }
7063 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007064 }
Mike Stump11289f42009-09-09 15:08:12 +00007065
Chris Lattnerdc226c22010-10-01 22:42:38 +00007066 // If there are modifiers and if we're allowed to parse them, go for it.
7067 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007068 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007069 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007070 default: Done = true; --Str; break;
7071 case '*':
7072 case '&': {
7073 // Both pointers and references can have their pointee types
7074 // qualified with an address space.
7075 char *End;
7076 unsigned AddrSpace = strtoul(Str, &End, 10);
7077 if (End != Str && AddrSpace != 0) {
7078 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7079 Str = End;
7080 }
7081 if (c == '*')
7082 Type = Context.getPointerType(Type);
7083 else
7084 Type = Context.getLValueReferenceType(Type);
7085 break;
7086 }
7087 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7088 case 'C':
7089 Type = Type.withConst();
7090 break;
7091 case 'D':
7092 Type = Context.getVolatileType(Type);
7093 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007094 case 'R':
7095 Type = Type.withRestrict();
7096 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007097 }
7098 }
Chris Lattner84733392010-10-01 07:13:18 +00007099
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007100 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007101 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007102
Chris Lattnerecd79c62009-06-14 00:45:47 +00007103 return Type;
7104}
7105
7106/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007107QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007108 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007109 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007110 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007111
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007112 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007113
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007114 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007115 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007116 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7117 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007118 if (Error != GE_None)
7119 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007120
7121 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7122
Chris Lattnerecd79c62009-06-14 00:45:47 +00007123 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007124 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007125 if (Error != GE_None)
7126 return QualType();
7127
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007128 // If this argument is required to be an IntegerConstantExpression and the
7129 // caller cares, fill in the bitmask we return.
7130 if (RequiresICE && IntegerConstantArgs)
7131 *IntegerConstantArgs |= 1 << ArgTypes.size();
7132
Chris Lattnerecd79c62009-06-14 00:45:47 +00007133 // Do array -> pointer decay. The builtin should use the decayed type.
7134 if (Ty->isArrayType())
7135 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007136
Chris Lattnerecd79c62009-06-14 00:45:47 +00007137 ArgTypes.push_back(Ty);
7138 }
7139
7140 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7141 "'.' should only occur at end of builtin type list!");
7142
John McCall991eb4b2010-12-21 00:44:39 +00007143 FunctionType::ExtInfo EI;
7144 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7145
7146 bool Variadic = (TypeStr[0] == '.');
7147
7148 // We really shouldn't be making a no-proto type here, especially in C++.
7149 if (ArgTypes.empty() && Variadic)
7150 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007151
John McCalldb40c7f2010-12-14 08:05:40 +00007152 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007153 EPI.ExtInfo = EI;
7154 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007155
7156 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007157}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007158
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007159GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7160 GVALinkage External = GVA_StrongExternal;
7161
7162 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007163 switch (L) {
7164 case NoLinkage:
7165 case InternalLinkage:
7166 case UniqueExternalLinkage:
7167 return GVA_Internal;
7168
7169 case ExternalLinkage:
7170 switch (FD->getTemplateSpecializationKind()) {
7171 case TSK_Undeclared:
7172 case TSK_ExplicitSpecialization:
7173 External = GVA_StrongExternal;
7174 break;
7175
7176 case TSK_ExplicitInstantiationDefinition:
7177 return GVA_ExplicitTemplateInstantiation;
7178
7179 case TSK_ExplicitInstantiationDeclaration:
7180 case TSK_ImplicitInstantiation:
7181 External = GVA_TemplateInstantiation;
7182 break;
7183 }
7184 }
7185
7186 if (!FD->isInlined())
7187 return External;
7188
David Blaikiebbafb8a2012-03-11 07:00:24 +00007189 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007190 // GNU or C99 inline semantics. Determine whether this symbol should be
7191 // externally visible.
7192 if (FD->isInlineDefinitionExternallyVisible())
7193 return External;
7194
7195 // C99 inline semantics, where the symbol is not externally visible.
7196 return GVA_C99Inline;
7197 }
7198
7199 // C++0x [temp.explicit]p9:
7200 // [ Note: The intent is that an inline function that is the subject of
7201 // an explicit instantiation declaration will still be implicitly
7202 // instantiated when used so that the body can be considered for
7203 // inlining, but that no out-of-line copy of the inline function would be
7204 // generated in the translation unit. -- end note ]
7205 if (FD->getTemplateSpecializationKind()
7206 == TSK_ExplicitInstantiationDeclaration)
7207 return GVA_C99Inline;
7208
7209 return GVA_CXXInline;
7210}
7211
7212GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7213 // If this is a static data member, compute the kind of template
7214 // specialization. Otherwise, this variable is not part of a
7215 // template.
7216 TemplateSpecializationKind TSK = TSK_Undeclared;
7217 if (VD->isStaticDataMember())
7218 TSK = VD->getTemplateSpecializationKind();
7219
7220 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007221 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007222 VD->getType()->getLinkage() == UniqueExternalLinkage)
7223 L = UniqueExternalLinkage;
7224
7225 switch (L) {
7226 case NoLinkage:
7227 case InternalLinkage:
7228 case UniqueExternalLinkage:
7229 return GVA_Internal;
7230
7231 case ExternalLinkage:
7232 switch (TSK) {
7233 case TSK_Undeclared:
7234 case TSK_ExplicitSpecialization:
7235 return GVA_StrongExternal;
7236
7237 case TSK_ExplicitInstantiationDeclaration:
7238 llvm_unreachable("Variable should not be instantiated");
7239 // Fall through to treat this like any other instantiation.
7240
7241 case TSK_ExplicitInstantiationDefinition:
7242 return GVA_ExplicitTemplateInstantiation;
7243
7244 case TSK_ImplicitInstantiation:
7245 return GVA_TemplateInstantiation;
7246 }
7247 }
7248
David Blaikie8a40f702012-01-17 06:56:22 +00007249 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007250}
7251
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007252bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007253 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7254 if (!VD->isFileVarDecl())
7255 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007256 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007257 return false;
7258
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007259 // Weak references don't produce any output by themselves.
7260 if (D->hasAttr<WeakRefAttr>())
7261 return false;
7262
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007263 // Aliases and used decls are required.
7264 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7265 return true;
7266
7267 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7268 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007269 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007270 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007271
7272 // Constructors and destructors are required.
7273 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7274 return true;
7275
7276 // The key function for a class is required.
7277 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7278 const CXXRecordDecl *RD = MD->getParent();
7279 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7280 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7281 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7282 return true;
7283 }
7284 }
7285
7286 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7287
7288 // static, static inline, always_inline, and extern inline functions can
7289 // always be deferred. Normal inline functions can be deferred in C99/C++.
7290 // Implicit template instantiations can also be deferred in C++.
7291 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007292 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007293 return false;
7294 return true;
7295 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007296
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007297 const VarDecl *VD = cast<VarDecl>(D);
7298 assert(VD->isFileVarDecl() && "Expected file scoped var");
7299
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007300 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7301 return false;
7302
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007303 // Structs that have non-trivial constructors or destructors are required.
7304
7305 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00007306 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007307 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7308 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00007309 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7310 RD->hasTrivialCopyConstructor() &&
7311 RD->hasTrivialMoveConstructor() &&
7312 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007313 return true;
7314 }
7315 }
7316
7317 GVALinkage L = GetGVALinkageForVariable(VD);
7318 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7319 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7320 return false;
7321 }
7322
7323 return true;
7324}
Charles Davis53c59df2010-08-16 03:33:14 +00007325
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007326CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007327 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007328 return ABI->getDefaultMethodCallConv(isVariadic);
7329}
7330
7331CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7332 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft)
7333 return CC_Default;
7334 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007335}
7336
Jay Foad39c79802011-01-12 09:06:06 +00007337bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007338 // Pass through to the C++ ABI object
7339 return ABI->isNearlyEmpty(RD);
7340}
7341
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007342MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00007343 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007344 case CXXABI_ARM:
7345 case CXXABI_Itanium:
7346 return createItaniumMangleContext(*this, getDiagnostics());
7347 case CXXABI_Microsoft:
7348 return createMicrosoftMangleContext(*this, getDiagnostics());
7349 }
David Blaikie83d382b2011-09-23 05:06:16 +00007350 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007351}
7352
Charles Davis53c59df2010-08-16 03:33:14 +00007353CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007354
7355size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007356 return ASTRecordLayouts.getMemorySize()
7357 + llvm::capacity_in_bytes(ObjCLayouts)
7358 + llvm::capacity_in_bytes(KeyFunctions)
7359 + llvm::capacity_in_bytes(ObjCImpls)
7360 + llvm::capacity_in_bytes(BlockVarCopyInits)
7361 + llvm::capacity_in_bytes(DeclAttrs)
7362 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7363 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7364 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7365 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7366 + llvm::capacity_in_bytes(OverriddenMethods)
7367 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007368 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007369 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007370}
Ted Kremenek540017e2011-10-06 05:00:56 +00007371
Douglas Gregor63798542012-02-20 19:44:39 +00007372unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7373 CXXRecordDecl *Lambda = CallOperator->getParent();
7374 return LambdaMangleContexts[Lambda->getDeclContext()]
7375 .getManglingNumber(CallOperator);
7376}
7377
7378
Ted Kremenek540017e2011-10-06 05:00:56 +00007379void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7380 ParamIndices[D] = index;
7381}
7382
7383unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7384 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7385 assert(I != ParamIndices.end() &&
7386 "ParmIndices lacks entry set by ParmVarDecl");
7387 return I->second;
7388}