blob: 2f8b8e66185ffe1f8f81b5245b87739229c378fe [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000032#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000035#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000036#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
66 CommentsLoaded = true;
67 }
68
69 assert(D);
70
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000071 // User can not attach documentation to implicit declarations.
72 if (D->isImplicit())
73 return NULL;
74
Dmitri Gribenkob2610882012-08-14 17:17:18 +000075 // User can not attach documentation to implicit instantiations.
76 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
77 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
78 return NULL;
79 }
80
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000081 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
82 if (VD->isStaticDataMember() &&
83 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
84 return NULL;
85 }
86
87 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
88 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
89 return NULL;
90 }
91
Dmitri Gribenko01b06512013-01-27 21:18:39 +000092 if (const ClassTemplateSpecializationDecl *CTSD =
93 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
94 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
95 if (TSK == TSK_ImplicitInstantiation ||
96 TSK == TSK_Undeclared)
97 return NULL;
98 }
99
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000100 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
101 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
102 return NULL;
103 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000104 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
105 // When tag declaration (but not definition!) is part of the
106 // decl-specifier-seq of some other declaration, it doesn't get comment
107 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
108 return NULL;
109 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000110 // TODO: handle comments for function parameters properly.
111 if (isa<ParmVarDecl>(D))
112 return NULL;
113
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000114 // TODO: we could look up template parameter documentation in the template
115 // documentation.
116 if (isa<TemplateTypeParmDecl>(D) ||
117 isa<NonTypeTemplateParmDecl>(D) ||
118 isa<TemplateTemplateParmDecl>(D))
119 return NULL;
120
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000121 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000122
123 // If there are no comments anywhere, we won't find anything.
124 if (RawComments.empty())
125 return NULL;
126
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000127 // Find declaration location.
128 // For Objective-C declarations we generally don't expect to have multiple
129 // declarators, thus use declaration starting location as the "declaration
130 // location".
131 // For all other declarations multiple declarators are used quite frequently,
132 // so we use the location of the identifier as the "declaration location".
133 SourceLocation DeclLoc;
134 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000135 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000136 isa<RedeclarableTemplateDecl>(D) ||
137 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000138 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000139 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000140 DeclLoc = D->getLocation();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000141 // If location of the typedef name is in a macro, it is because being
142 // declared via a macro. Try using declaration's starting location
143 // as the "declaration location".
144 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
145 DeclLoc = D->getLocStart();
146 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000148 // If the declaration doesn't map directly to a location in a file, we
149 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000150 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
151 return NULL;
152
153 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000154 ArrayRef<RawComment *>::iterator Comment;
155 {
156 // When searching for comments during parsing, the comment we are looking
157 // for is usually among the last two comments we parsed -- check them
158 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000159 RawComment CommentAtDeclLoc(
160 SourceMgr, SourceRange(DeclLoc), false,
161 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000162 BeforeThanCompare<RawComment> Compare(SourceMgr);
163 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
164 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
165 if (!Found && RawComments.size() >= 2) {
166 MaybeBeforeDecl--;
167 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
168 }
169
170 if (Found) {
171 Comment = MaybeBeforeDecl + 1;
172 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
173 &CommentAtDeclLoc, Compare));
174 } else {
175 // Slow path.
176 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
177 &CommentAtDeclLoc, Compare);
178 }
179 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000180
181 // Decompose the location for the declaration and find the beginning of the
182 // file buffer.
183 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
184
185 // First check whether we have a trailing comment.
186 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000187 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000188 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000189 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000190 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000191 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000192 // Check that Doxygen trailing comment comes after the declaration, starts
193 // on the same line and in the same file as the declaration.
194 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
195 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
196 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
197 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000198 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199 }
200 }
201
202 // The comment just after the declaration was not a trailing comment.
203 // Let's look at the previous comment.
204 if (Comment == RawComments.begin())
205 return NULL;
206 --Comment;
207
208 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000209 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000210 return NULL;
211
212 // Decompose the end of the comment.
213 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000214 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000215
216 // If the comment and the declaration aren't in the same file, then they
217 // aren't related.
218 if (DeclLocDecomp.first != CommentEndDecomp.first)
219 return NULL;
220
221 // Get the corresponding buffer.
222 bool Invalid = false;
223 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
224 &Invalid).data();
225 if (Invalid)
226 return NULL;
227
228 // Extract text between the comment and declaration.
229 StringRef Text(Buffer + CommentEndDecomp.second,
230 DeclLocDecomp.second - CommentEndDecomp.second);
231
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000232 // There should be no other declarations or preprocessor directives between
233 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000234 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000235 return NULL;
236
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000237 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000238}
239
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000240namespace {
241/// If we have a 'templated' declaration for a template, adjust 'D' to
242/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000243/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000244const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000245 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000246 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000247 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000248 return FTD;
249
250 // Nothing to do if function is not an implicit instantiation.
251 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
252 return D;
253
254 // Function is an implicit instantiation of a function template?
255 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
256 return FTD;
257
258 // Function is instantiated from a member definition of a class template?
259 if (const FunctionDecl *MemberDecl =
260 FD->getInstantiatedFromMemberFunction())
261 return MemberDecl;
262
263 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
266 // Static data member is instantiated from a member definition of a class
267 // template?
268 if (VD->isStaticDataMember())
269 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
270 return MemberDecl;
271
272 return D;
273 }
274 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
275 // Is this class declaration part of a class template?
276 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
277 return CTD;
278
279 // Class is an implicit instantiation of a class template or partial
280 // specialization?
281 if (const ClassTemplateSpecializationDecl *CTSD =
282 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
283 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
284 return D;
285 llvm::PointerUnion<ClassTemplateDecl *,
286 ClassTemplatePartialSpecializationDecl *>
287 PU = CTSD->getSpecializedTemplateOrPartial();
288 return PU.is<ClassTemplateDecl*>() ?
289 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
290 static_cast<const Decl*>(
291 PU.get<ClassTemplatePartialSpecializationDecl *>());
292 }
293
294 // Class is instantiated from a member definition of a class template?
295 if (const MemberSpecializationInfo *Info =
296 CRD->getMemberSpecializationInfo())
297 return Info->getInstantiatedFrom();
298
299 return D;
300 }
301 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
302 // Enum is instantiated from a member definition of a class template?
303 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
304 return MemberDecl;
305
306 return D;
307 }
308 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000309 return D;
310}
311} // unnamed namespace
312
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000313const RawComment *ASTContext::getRawCommentForAnyRedecl(
314 const Decl *D,
315 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000316 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000317
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000318 // Check whether we have cached a comment for this declaration already.
319 {
320 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
321 RedeclComments.find(D);
322 if (Pos != RedeclComments.end()) {
323 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000324 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
325 if (OriginalDecl)
326 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000327 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000328 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000329 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000330 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000331
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000332 // Search for comments attached to declarations in the redeclaration chain.
333 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000334 const Decl *OriginalDeclForRC = NULL;
Aaron Ballman86c93902014-03-06 23:45:36 +0000335 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000336 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000337 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000338 if (Pos != RedeclComments.end()) {
339 const RawCommentAndCacheFlags &Raw = Pos->second;
340 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
341 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000342 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000343 break;
344 }
345 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000346 RC = getRawCommentForDeclNoCache(I);
347 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 RawCommentAndCacheFlags Raw;
349 if (RC) {
350 Raw.setRaw(RC);
351 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
352 } else
353 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 Raw.setOriginalDecl(I);
355 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000356 if (RC)
357 break;
358 }
359 }
360
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000361 // If we found a comment, it should be a documentation comment.
362 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000363
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000364 if (OriginalDecl)
365 *OriginalDecl = OriginalDeclForRC;
366
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 // Update cache for every declaration in the redeclaration chain.
368 RawCommentAndCacheFlags Raw;
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000371 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000372
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 for (auto I : D->redecls()) {
374 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
376 R = Raw;
377 }
378
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000379 return RC;
380}
381
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000382static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
383 SmallVectorImpl<const NamedDecl *> &Redeclared) {
384 const DeclContext *DC = ObjCMethod->getDeclContext();
385 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
386 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
387 if (!ID)
388 return;
389 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000390 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000391 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000392 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000393 ObjCMethod->isInstanceMethod()))
394 Redeclared.push_back(RedeclaredMethod);
395 }
396 }
397}
398
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000399comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
400 const Decl *D) const {
401 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
402 ThisDeclInfo->CommentDecl = D;
403 ThisDeclInfo->IsFilled = false;
404 ThisDeclInfo->fill();
405 ThisDeclInfo->CommentDecl = FC->getDecl();
406 comments::FullComment *CFC =
407 new (*this) comments::FullComment(FC->getBlocks(),
408 ThisDeclInfo);
409 return CFC;
410
411}
412
Richard Smithb39b9d52013-05-21 05:24:00 +0000413comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
414 const RawComment *RC = getRawCommentForDeclNoCache(D);
415 return RC ? RC->parse(*this, 0, D) : 0;
416}
417
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000418comments::FullComment *ASTContext::getCommentForDecl(
419 const Decl *D,
420 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000421 if (D->isInvalidDecl())
422 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000423 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000424
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000425 const Decl *Canonical = D->getCanonicalDecl();
426 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
427 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000428
429 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000430 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000431 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000432 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000433 return CFC;
434 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000435 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000436 }
437
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000438 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000439
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000440 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000441 if (!RC) {
442 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000443 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000444 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000445 if (OMD && OMD->isPropertyAccessor())
446 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
447 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
448 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000449 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000450 addRedeclaredMethods(OMD, Overridden);
451 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000452 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
453 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
454 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000456 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000457 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000458 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000459 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000460 if (const TagType *TT = QT->getAs<TagType>())
461 if (const Decl *TD = TT->getDecl())
462 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000463 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000464 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000465 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
466 while (IC->getSuperClass()) {
467 IC = IC->getSuperClass();
468 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
469 return cloneFullComment(FC, D);
470 }
471 }
472 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
473 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
474 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
475 return cloneFullComment(FC, D);
476 }
477 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
478 if (!(RD = RD->getDefinition()))
479 return NULL;
480 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000481 for (const auto &I : RD->bases()) {
482 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000483 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000484 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000485 if (Ty.isNull())
486 continue;
487 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
488 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
489 continue;
490
491 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
492 return cloneFullComment(FC, D);
493 }
494 }
495 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000496 for (const auto &I : RD->vbases()) {
497 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000498 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000499 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000500 if (Ty.isNull())
501 continue;
502 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
503 if (!(VirtualBase= VirtualBase->getDefinition()))
504 continue;
505 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
506 return cloneFullComment(FC, D);
507 }
508 }
509 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000510 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000511 }
512
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000513 // If the RawComment was attached to other redeclaration of this Decl, we
514 // should parse the comment in context of that other Decl. This is important
515 // because comments can contain references to parameter names which can be
516 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000517 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000518 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000519
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000520 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000521 ParsedComments[Canonical] = FC;
522 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000523}
524
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000525void
526ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
527 TemplateTemplateParmDecl *Parm) {
528 ID.AddInteger(Parm->getDepth());
529 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000530 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000531
532 TemplateParameterList *Params = Parm->getTemplateParameters();
533 ID.AddInteger(Params->size());
534 for (TemplateParameterList::const_iterator P = Params->begin(),
535 PEnd = Params->end();
536 P != PEnd; ++P) {
537 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
538 ID.AddInteger(0);
539 ID.AddBoolean(TTP->isParameterPack());
540 continue;
541 }
542
543 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
544 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000545 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000546 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000547 if (NTTP->isExpandedParameterPack()) {
548 ID.AddBoolean(true);
549 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000550 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
551 QualType T = NTTP->getExpansionType(I);
552 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
553 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000554 } else
555 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000556 continue;
557 }
558
559 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
560 ID.AddInteger(2);
561 Profile(ID, TTP);
562 }
563}
564
565TemplateTemplateParmDecl *
566ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000567 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000568 // Check if we already have a canonical template template parameter.
569 llvm::FoldingSetNodeID ID;
570 CanonicalTemplateTemplateParm::Profile(ID, TTP);
571 void *InsertPos = 0;
572 CanonicalTemplateTemplateParm *Canonical
573 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
574 if (Canonical)
575 return Canonical->getParam();
576
577 // Build a canonical template parameter list.
578 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000579 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000580 CanonParams.reserve(Params->size());
581 for (TemplateParameterList::const_iterator P = Params->begin(),
582 PEnd = Params->end();
583 P != PEnd; ++P) {
584 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
585 CanonParams.push_back(
586 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000587 SourceLocation(),
588 SourceLocation(),
589 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 TTP->getIndex(), 0, false,
591 TTP->isParameterPack()));
592 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000593 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
594 QualType T = getCanonicalType(NTTP->getType());
595 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
596 NonTypeTemplateParmDecl *Param;
597 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000598 SmallVector<QualType, 2> ExpandedTypes;
599 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000600 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
601 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
602 ExpandedTInfos.push_back(
603 getTrivialTypeSourceInfo(ExpandedTypes.back()));
604 }
605
606 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000607 SourceLocation(),
608 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000609 NTTP->getDepth(),
610 NTTP->getPosition(), 0,
611 T,
612 TInfo,
613 ExpandedTypes.data(),
614 ExpandedTypes.size(),
615 ExpandedTInfos.data());
616 } else {
617 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000618 SourceLocation(),
619 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000620 NTTP->getDepth(),
621 NTTP->getPosition(), 0,
622 T,
623 NTTP->isParameterPack(),
624 TInfo);
625 }
626 CanonParams.push_back(Param);
627
628 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000629 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
630 cast<TemplateTemplateParmDecl>(*P)));
631 }
632
633 TemplateTemplateParmDecl *CanonTTP
634 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
635 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000636 TTP->getPosition(),
637 TTP->isParameterPack(),
638 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000639 TemplateParameterList::Create(*this, SourceLocation(),
640 SourceLocation(),
641 CanonParams.data(),
642 CanonParams.size(),
643 SourceLocation()));
644
645 // Get the new insert position for the node we care about.
646 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
647 assert(Canonical == 0 && "Shouldn't be in the map!");
648 (void)Canonical;
649
650 // Create the canonical template template parameter entry.
651 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
652 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
653 return CanonTTP;
654}
655
Charles Davis53c59df2010-08-16 03:33:14 +0000656CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000657 if (!LangOpts.CPlusPlus) return 0;
658
John McCall359b8852013-01-25 22:30:49 +0000659 switch (T.getCXXABI().getKind()) {
660 case TargetCXXABI::GenericARM:
661 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000662 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000663 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000664 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000665 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000666 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000667 return CreateMicrosoftCXXABI(*this);
668 }
David Blaikie8a40f702012-01-17 06:56:22 +0000669 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000670}
671
Douglas Gregore8bbc122011-09-02 00:18:52 +0000672static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000673 const LangOptions &LOpts) {
674 if (LOpts.FakeAddressSpaceMap) {
675 // The fake address space map must have a distinct entry for each
676 // language-specific address space.
677 static const unsigned FakeAddrSpaceMap[] = {
678 1, // opencl_global
679 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000680 3, // opencl_constant
681 4, // cuda_device
682 5, // cuda_constant
683 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000684 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000685 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000686 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000687 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000688 }
689}
690
David Tweed31d09b02013-09-13 12:04:22 +0000691static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
692 const LangOptions &LangOpts) {
693 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000694 case LangOptions::ASMM_Target:
695 return TI.useAddressSpaceMapMangling();
696 case LangOptions::ASMM_On:
697 return true;
698 case LangOptions::ASMM_Off:
699 return false;
700 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000701 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000702}
703
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000704ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000705 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000706 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000707 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 unsigned size_reserve,
709 bool DelayInitialization)
710 : FunctionProtoTypes(this_()),
711 TemplateSpecializationTypes(this_()),
712 DependentTemplateSpecializationTypes(this_()),
713 SubstTemplateTemplateParmPacks(this_()),
714 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000715 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000716 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000717 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000718 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000719 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000720 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000721 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
722 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
723 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000724 NullTypeSourceInfo(QualType()),
725 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000726 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000727 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 Idents(idents), Selectors(sels),
729 BuiltinInfo(builtins),
730 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000731 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000732 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000733 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000734 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000735{
Mike Stump11289f42009-09-09 15:08:12 +0000736 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000737 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000738
739 if (!DelayInitialization) {
740 assert(t && "No target supplied for ASTContext initialization");
741 InitBuiltinTypes(*t);
742 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000743}
744
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000745ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000746 // Release the DenseMaps associated with DeclContext objects.
747 // FIXME: Is this the ideal solution?
748 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000749
Manuel Klimeka7328992013-06-03 13:51:33 +0000750 // Call all of the deallocation functions on all of their targets.
751 for (DeallocationMap::const_iterator I = Deallocations.begin(),
752 E = Deallocations.end(); I != E; ++I)
753 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
754 (I->first)((I->second)[J]);
755
Ted Kremenek076baeb2010-06-08 23:00:58 +0000756 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000757 // because they can contain DenseMaps.
758 for (llvm::DenseMap<const ObjCContainerDecl*,
759 const ASTRecordLayout*>::iterator
760 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
761 // Increment in loop to prevent using deallocated memory.
762 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
763 R->Destroy(*this);
764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
766 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
767 // Increment in loop to prevent using deallocated memory.
768 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
769 R->Destroy(*this);
770 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000771
772 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
773 AEnd = DeclAttrs.end();
774 A != AEnd; ++A)
775 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000776
Reid Kleckner588c9372014-02-19 23:44:52 +0000777 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000778}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000779
Douglas Gregor1a809332010-05-23 18:26:36 +0000780void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000781 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000782}
783
Mike Stump11289f42009-09-09 15:08:12 +0000784void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000785ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
786 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000787}
788
Chris Lattner4eb445d2007-01-26 01:27:23 +0000789void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000790 llvm::errs() << "\n*** AST Context Stats:\n";
791 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000792
Douglas Gregora30d0462009-05-26 14:40:08 +0000793 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000794#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000795#define ABSTRACT_TYPE(Name, Parent)
796#include "clang/AST/TypeNodes.def"
797 0 // Extra
798 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000799
Chris Lattner4eb445d2007-01-26 01:27:23 +0000800 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
801 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000802 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000803 }
804
Douglas Gregora30d0462009-05-26 14:40:08 +0000805 unsigned Idx = 0;
806 unsigned TotalBytes = 0;
807#define TYPE(Name, Parent) \
808 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000809 llvm::errs() << " " << counts[Idx] << " " << #Name \
810 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000811 TotalBytes += counts[Idx] * sizeof(Name##Type); \
812 ++Idx;
813#define ABSTRACT_TYPE(Name, Parent)
814#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chandler Carruth3c147a72011-07-04 05:32:14 +0000816 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
817
Douglas Gregor7454c562010-07-02 20:37:36 +0000818 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000819 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
820 << NumImplicitDefaultConstructors
821 << " implicit default constructors created\n";
822 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
823 << NumImplicitCopyConstructors
824 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000825 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000826 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
827 << NumImplicitMoveConstructors
828 << " implicit move constructors created\n";
829 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
830 << NumImplicitCopyAssignmentOperators
831 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000832 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000833 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
834 << NumImplicitMoveAssignmentOperators
835 << " implicit move assignment operators created\n";
836 llvm::errs() << NumImplicitDestructorsDeclared << "/"
837 << NumImplicitDestructors
838 << " implicit destructors created\n";
839
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000840 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000841 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000842 ExternalSource->PrintStats();
843 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000844
Douglas Gregor5b11d492010-07-25 17:53:33 +0000845 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000846}
847
Alp Toker2dea15b2013-12-17 01:22:38 +0000848RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
849 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000850 SourceLocation Loc;
851 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000852 if (getLangOpts().CPlusPlus)
853 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
854 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000855 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000856 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
857 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000858 NewDecl->setImplicit();
859 return NewDecl;
860}
861
862TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
863 StringRef Name) const {
864 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
865 TypedefDecl *NewDecl = TypedefDecl::Create(
866 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
867 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
868 NewDecl->setImplicit();
869 return NewDecl;
870}
871
Douglas Gregor801c99d2011-08-12 06:49:56 +0000872TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000873 if (!Int128Decl)
874 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000875 return Int128Decl;
876}
877
878TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000879 if (!UInt128Decl)
880 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000881 return UInt128Decl;
882}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000883
Nico Webere1687c52013-06-20 21:44:55 +0000884TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000885 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000886 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000887 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000888
Nico Webere1687c52013-06-20 21:44:55 +0000889 return Float128StubDecl;
890}
891
John McCall48f2d582009-10-23 23:03:21 +0000892void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000893 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000894 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000895 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000896}
897
Douglas Gregore8bbc122011-09-02 00:18:52 +0000898void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
899 assert((!this->Target || this->Target == &Target) &&
900 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000901 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000902
Douglas Gregore8bbc122011-09-02 00:18:52 +0000903 this->Target = &Target;
904
905 ABI.reset(createCXXABI(Target));
906 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000907 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000908
Chris Lattner970e54e2006-11-12 00:37:36 +0000909 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000910 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000911
Chris Lattner970e54e2006-11-12 00:37:36 +0000912 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000913 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000914 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000915 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000916 InitBuiltinType(CharTy, BuiltinType::Char_S);
917 else
918 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000919 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000920 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
921 InitBuiltinType(ShortTy, BuiltinType::Short);
922 InitBuiltinType(IntTy, BuiltinType::Int);
923 InitBuiltinType(LongTy, BuiltinType::Long);
924 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000925
Chris Lattner970e54e2006-11-12 00:37:36 +0000926 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000927 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
928 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
929 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
930 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
931 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000932
Chris Lattner970e54e2006-11-12 00:37:36 +0000933 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000934 InitBuiltinType(FloatTy, BuiltinType::Float);
935 InitBuiltinType(DoubleTy, BuiltinType::Double);
936 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000937
Chris Lattnerf122cef2009-04-30 02:43:43 +0000938 // GNU extension, 128-bit integers.
939 InitBuiltinType(Int128Ty, BuiltinType::Int128);
940 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
941
Hans Wennborg0d81e012013-05-10 10:08:40 +0000942 // C++ 3.9.1p5
943 if (TargetInfo::isTypeSigned(Target.getWCharType()))
944 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
945 else // -fshort-wchar makes wchar_t be unsigned.
946 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
947 if (LangOpts.CPlusPlus && LangOpts.WChar)
948 WideCharTy = WCharTy;
949 else {
950 // C99 (or C++ using -fno-wchar).
951 WideCharTy = getFromTargetType(Target.getWCharType());
952 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000953
James Molloy36365542012-05-04 10:55:22 +0000954 WIntTy = getFromTargetType(Target.getWIntType());
955
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000956 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
957 InitBuiltinType(Char16Ty, BuiltinType::Char16);
958 else // C99
959 Char16Ty = getFromTargetType(Target.getChar16Type());
960
961 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
962 InitBuiltinType(Char32Ty, BuiltinType::Char32);
963 else // C99
964 Char32Ty = getFromTargetType(Target.getChar32Type());
965
Douglas Gregor4619e432008-12-05 23:32:09 +0000966 // Placeholder type for type-dependent expressions whose type is
967 // completely unknown. No code should ever check a type against
968 // DependentTy and users should never see it; however, it is here to
969 // help diagnose failures to properly check for type-dependent
970 // expressions.
971 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000972
John McCall36e7fe32010-10-12 00:20:44 +0000973 // Placeholder type for functions.
974 InitBuiltinType(OverloadTy, BuiltinType::Overload);
975
John McCall0009fcc2011-04-26 20:42:42 +0000976 // Placeholder type for bound members.
977 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
978
John McCall526ab472011-10-25 17:37:35 +0000979 // Placeholder type for pseudo-objects.
980 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
981
John McCall31996342011-04-07 08:22:57 +0000982 // "any" type; useful for debugger-like clients.
983 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
984
John McCall8a6b59a2011-10-17 18:09:15 +0000985 // Placeholder type for unbridged ARC casts.
986 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
987
Eli Friedman34866c72012-08-31 00:14:07 +0000988 // Placeholder type for builtin functions.
989 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
990
Chris Lattner970e54e2006-11-12 00:37:36 +0000991 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000992 FloatComplexTy = getComplexType(FloatTy);
993 DoubleComplexTy = getComplexType(DoubleTy);
994 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000995
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000996 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000997 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
998 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000999 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001000
1001 if (LangOpts.OpenCL) {
1002 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1003 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1004 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1005 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1006 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1007 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001008
Guy Benyei61054192013-02-07 10:55:47 +00001009 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001010 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001011 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001012
1013 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001014 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1015 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001016
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001017 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001018
1019 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001020
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001021 // void * type
1022 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001023
1024 // nullptr type (C++0x 2.14.7)
1025 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001026
1027 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1028 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001029
1030 // Builtin type used to help define __builtin_va_list.
1031 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001032}
1033
David Blaikie9c902b52011-09-25 23:23:43 +00001034DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001035 return SourceMgr.getDiagnostics();
1036}
1037
Douglas Gregor561eceb2010-08-30 16:49:28 +00001038AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1039 AttrVec *&Result = DeclAttrs[D];
1040 if (!Result) {
1041 void *Mem = Allocate(sizeof(AttrVec));
1042 Result = new (Mem) AttrVec;
1043 }
1044
1045 return *Result;
1046}
1047
1048/// \brief Erase the attributes corresponding to the given declaration.
1049void ASTContext::eraseDeclAttrs(const Decl *D) {
1050 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1051 if (Pos != DeclAttrs.end()) {
1052 Pos->second->~AttrVec();
1053 DeclAttrs.erase(Pos);
1054 }
1055}
1056
Larisse Voufo39a1e502013-08-06 01:03:05 +00001057// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001058MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001059ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001060 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001061 return getTemplateOrSpecializationInfo(Var)
1062 .dyn_cast<MemberSpecializationInfo *>();
1063}
1064
1065ASTContext::TemplateOrSpecializationInfo
1066ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1067 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1068 TemplateOrInstantiation.find(Var);
1069 if (Pos == TemplateOrInstantiation.end())
1070 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001071
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001072 return Pos->second;
1073}
1074
Mike Stump11289f42009-09-09 15:08:12 +00001075void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001076ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001077 TemplateSpecializationKind TSK,
1078 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001079 assert(Inst->isStaticDataMember() && "Not a static data member");
1080 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001081 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1082 Tmpl, TSK, PointOfInstantiation));
1083}
1084
1085void
1086ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1087 TemplateOrSpecializationInfo TSI) {
1088 assert(!TemplateOrInstantiation[Inst] &&
1089 "Already noted what the variable was instantiated from");
1090 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001091}
1092
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001093FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1094 const FunctionDecl *FD){
1095 assert(FD && "Specialization is 0");
1096 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001097 = ClassScopeSpecializationPattern.find(FD);
1098 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001099 return 0;
1100
1101 return Pos->second;
1102}
1103
1104void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1105 FunctionDecl *Pattern) {
1106 assert(FD && "Specialization is 0");
1107 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001108 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001109}
1110
John McCalle61f2ba2009-11-18 02:36:19 +00001111NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001112ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001113 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001114 = InstantiatedFromUsingDecl.find(UUD);
1115 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001116 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001117
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001118 return Pos->second;
1119}
1120
1121void
John McCallb96ec562009-12-04 22:46:56 +00001122ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1123 assert((isa<UsingDecl>(Pattern) ||
1124 isa<UnresolvedUsingValueDecl>(Pattern) ||
1125 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1126 "pattern decl is not a using decl");
1127 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1128 InstantiatedFromUsingDecl[Inst] = Pattern;
1129}
1130
1131UsingShadowDecl *
1132ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1133 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1134 = InstantiatedFromUsingShadowDecl.find(Inst);
1135 if (Pos == InstantiatedFromUsingShadowDecl.end())
1136 return 0;
1137
1138 return Pos->second;
1139}
1140
1141void
1142ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1143 UsingShadowDecl *Pattern) {
1144 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1145 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001146}
1147
Anders Carlsson5da84842009-09-01 04:26:58 +00001148FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1149 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1150 = InstantiatedFromUnnamedFieldDecl.find(Field);
1151 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1152 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001153
Anders Carlsson5da84842009-09-01 04:26:58 +00001154 return Pos->second;
1155}
1156
1157void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1158 FieldDecl *Tmpl) {
1159 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1160 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1161 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1162 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001163
Anders Carlsson5da84842009-09-01 04:26:58 +00001164 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1165}
1166
Douglas Gregor832940b2010-03-02 23:58:15 +00001167ASTContext::overridden_cxx_method_iterator
1168ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1169 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001170 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001171 if (Pos == OverriddenMethods.end())
1172 return 0;
1173
1174 return Pos->second.begin();
1175}
1176
1177ASTContext::overridden_cxx_method_iterator
1178ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1179 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001180 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001181 if (Pos == OverriddenMethods.end())
1182 return 0;
1183
1184 return Pos->second.end();
1185}
1186
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001187unsigned
1188ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001190 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001191 if (Pos == OverriddenMethods.end())
1192 return 0;
1193
1194 return Pos->second.size();
1195}
1196
Douglas Gregor832940b2010-03-02 23:58:15 +00001197void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1198 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001199 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001200 OverriddenMethods[Method].push_back(Overridden);
1201}
1202
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001203void ASTContext::getOverriddenMethods(
1204 const NamedDecl *D,
1205 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001206 assert(D);
1207
1208 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001209 Overridden.append(overridden_methods_begin(CXXMethod),
1210 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001211 return;
1212 }
1213
1214 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1215 if (!Method)
1216 return;
1217
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001218 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1219 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001220 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001221}
1222
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001223void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1224 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1225 assert(!Import->isFromASTFile() && "Non-local import declaration");
1226 if (!FirstLocalImport) {
1227 FirstLocalImport = Import;
1228 LastLocalImport = Import;
1229 return;
1230 }
1231
1232 LastLocalImport->NextLocalImport = Import;
1233 LastLocalImport = Import;
1234}
1235
Chris Lattner53cfe802007-07-18 17:52:12 +00001236//===----------------------------------------------------------------------===//
1237// Type Sizing and Analysis
1238//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001239
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001240/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1241/// scalar floating point type.
1242const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001243 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001244 assert(BT && "Not a floating point type!");
1245 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001246 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001247 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001248 case BuiltinType::Float: return Target->getFloatFormat();
1249 case BuiltinType::Double: return Target->getDoubleFormat();
1250 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001251 }
1252}
1253
Rafael Espindola71eccb32013-08-08 19:53:46 +00001254CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001255 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001256
John McCall94268702010-10-08 18:24:19 +00001257 bool UseAlignAttrOnly = false;
1258 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1259 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001260
John McCall94268702010-10-08 18:24:19 +00001261 // __attribute__((aligned)) can increase or decrease alignment
1262 // *except* on a struct or struct member, where it only increases
1263 // alignment unless 'packed' is also specified.
1264 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001265 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001266 // ignore that possibility; Sema should diagnose it.
1267 if (isa<FieldDecl>(D)) {
1268 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1269 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1270 } else {
1271 UseAlignAttrOnly = true;
1272 }
1273 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001274 else if (isa<FieldDecl>(D))
1275 UseAlignAttrOnly =
1276 D->hasAttr<PackedAttr>() ||
1277 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001278
John McCall4e819612011-01-20 07:57:12 +00001279 // If we're using the align attribute only, just ignore everything
1280 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001281 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001282 // do nothing
1283
John McCall94268702010-10-08 18:24:19 +00001284 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001285 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001286 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001287 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001288 T = RT->getPointeeType();
1289 else
1290 T = getPointerType(RT->getPointeeType());
1291 }
1292 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001293 // Adjust alignments of declarations with array type by the
1294 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001295 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001296 unsigned MinWidth = Target->getLargeArrayMinWidth();
1297 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001298 if (isa<VariableArrayType>(arrayType))
1299 Align = std::max(Align, Target->getLargeArrayAlign());
1300 else if (isa<ConstantArrayType>(arrayType) &&
1301 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1302 Align = std::max(Align, Target->getLargeArrayAlign());
1303 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001304
John McCall33ddac02011-01-19 10:06:00 +00001305 // Walk through any array types while we're at it.
1306 T = getBaseElementType(arrayType);
1307 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001308 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001309 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1310 if (VD->hasGlobalStorage())
1311 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1312 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001313 }
John McCall4e819612011-01-20 07:57:12 +00001314
1315 // Fields can be subject to extra alignment constraints, like if
1316 // the field is packed, the struct is packed, or the struct has a
1317 // a max-field-alignment constraint (#pragma pack). So calculate
1318 // the actual alignment of the field within the struct, and then
1319 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001320 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1321 const RecordDecl *Parent = Field->getParent();
1322 // We can only produce a sensible answer if the record is valid.
1323 if (!Parent->isInvalidDecl()) {
1324 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001325
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001326 // Start with the record's overall alignment.
1327 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001328
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001329 // Use the GCD of that and the offset within the record.
1330 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1331 if (Offset > 0) {
1332 // Alignment is always a power of 2, so the GCD will be a power of 2,
1333 // which means we get to do this crazy thing instead of Euclid's.
1334 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1335 if (LowBitOfOffset < FieldAlign)
1336 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1337 }
1338
1339 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001340 }
Charles Davis3fc51072010-02-23 04:52:00 +00001341 }
Chris Lattner68061312009-01-24 21:53:27 +00001342 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001343
Ken Dyckcc56c542011-01-15 18:38:59 +00001344 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001345}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001346
John McCallf1249922012-08-21 04:10:00 +00001347// getTypeInfoDataSizeInChars - Return the size of a type, in
1348// chars. If the type is a record, its data size is returned. This is
1349// the size of the memcpy that's performed when assigning this type
1350// using a trivial copy/move assignment operator.
1351std::pair<CharUnits, CharUnits>
1352ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1353 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1354
1355 // In C++, objects can sometimes be allocated into the tail padding
1356 // of a base-class subobject. We decide whether that's possible
1357 // during class layout, so here we can just trust the layout results.
1358 if (getLangOpts().CPlusPlus) {
1359 if (const RecordType *RT = T->getAs<RecordType>()) {
1360 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1361 sizeAndAlign.first = layout.getDataSize();
1362 }
1363 }
1364
1365 return sizeAndAlign;
1366}
1367
Richard Trieu04d2d942013-05-14 21:59:17 +00001368/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1369/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1370std::pair<CharUnits, CharUnits>
1371static getConstantArrayInfoInChars(const ASTContext &Context,
1372 const ConstantArrayType *CAT) {
1373 std::pair<CharUnits, CharUnits> EltInfo =
1374 Context.getTypeInfoInChars(CAT->getElementType());
1375 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001376 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1377 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001378 "Overflow in array type char size evaluation");
1379 uint64_t Width = EltInfo.first.getQuantity() * Size;
1380 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001381 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1382 Context.getTargetInfo().getPointerWidth(0) == 64)
1383 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001384 return std::make_pair(CharUnits::fromQuantity(Width),
1385 CharUnits::fromQuantity(Align));
1386}
1387
John McCall87fe5d52010-05-20 01:18:31 +00001388std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001389ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001390 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1391 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001392 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001393 return std::make_pair(toCharUnitsFromBits(Info.first),
1394 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001395}
1396
1397std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001398ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001399 return getTypeInfoInChars(T.getTypePtr());
1400}
1401
Daniel Dunbarc6475872012-03-09 04:12:54 +00001402std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1403 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1404 if (it != MemoizedTypeInfo.end())
1405 return it->second;
1406
1407 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1408 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1409 return Info;
1410}
1411
1412/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1413/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001414///
1415/// FIXME: Pointers into different addr spaces could have different sizes and
1416/// alignment requirements: getPointerInfo should take an AddrSpace, this
1417/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001418std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001419ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001420 uint64_t Width=0;
1421 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001422 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001423#define TYPE(Class, Base)
1424#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001425#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001426#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001427#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1428 case Type::Class: \
1429 assert(!T->isDependentType() && "should not see dependent types here"); \
1430 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001431#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001432 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001433
Chris Lattner355332d2007-07-13 22:27:08 +00001434 case Type::FunctionNoProto:
1435 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001436 // GCC extension: alignof(function) = 32 bits
1437 Width = 0;
1438 Align = 32;
1439 break;
1440
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001441 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001442 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001443 Width = 0;
1444 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1445 break;
1446
Steve Naroff5c131802007-08-30 01:06:46 +00001447 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001448 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001449
Chris Lattner37e05872008-03-05 18:54:05 +00001450 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001451 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001452 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1453 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001454 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001455 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001456 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1457 getTargetInfo().getPointerWidth(0) == 64)
1458 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001459 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001460 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001461 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001462 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001463 const VectorType *VT = cast<VectorType>(T);
1464 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1465 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001466 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001467 // If the alignment is not a power of 2, round up to the next power of 2.
1468 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001469 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001470 Align = llvm::NextPowerOf2(Align);
1471 Width = llvm::RoundUpToAlignment(Width, Align);
1472 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001473 // Adjust the alignment based on the target max.
1474 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1475 if (TargetVectorAlign && TargetVectorAlign < Align)
1476 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001477 break;
1478 }
Chris Lattner647fb222007-07-18 18:26:58 +00001479
Chris Lattner7570e9c2008-03-08 08:52:55 +00001480 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001481 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001482 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001483 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001484 // GCC extension: alignof(void) = 8 bits.
1485 Width = 0;
1486 Align = 8;
1487 break;
1488
Chris Lattner6a4f7452007-12-19 19:23:28 +00001489 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001490 Width = Target->getBoolWidth();
1491 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001492 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001493 case BuiltinType::Char_S:
1494 case BuiltinType::Char_U:
1495 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001496 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001497 Width = Target->getCharWidth();
1498 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001499 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001500 case BuiltinType::WChar_S:
1501 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001502 Width = Target->getWCharWidth();
1503 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001504 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001505 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001506 Width = Target->getChar16Width();
1507 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001508 break;
1509 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001510 Width = Target->getChar32Width();
1511 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001512 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001513 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001514 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001515 Width = Target->getShortWidth();
1516 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001517 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001518 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001519 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001520 Width = Target->getIntWidth();
1521 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001522 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001523 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001524 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001525 Width = Target->getLongWidth();
1526 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001527 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001528 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001529 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001530 Width = Target->getLongLongWidth();
1531 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001532 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001533 case BuiltinType::Int128:
1534 case BuiltinType::UInt128:
1535 Width = 128;
1536 Align = 128; // int128_t is 128-bit aligned on all targets.
1537 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001538 case BuiltinType::Half:
1539 Width = Target->getHalfWidth();
1540 Align = Target->getHalfAlign();
1541 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001542 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001543 Width = Target->getFloatWidth();
1544 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001545 break;
1546 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001547 Width = Target->getDoubleWidth();
1548 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001549 break;
1550 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001551 Width = Target->getLongDoubleWidth();
1552 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001553 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001554 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001555 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1556 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001557 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001558 case BuiltinType::ObjCId:
1559 case BuiltinType::ObjCClass:
1560 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001561 Width = Target->getPointerWidth(0);
1562 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001563 break;
Guy Benyei61054192013-02-07 10:55:47 +00001564 case BuiltinType::OCLSampler:
1565 // Samplers are modeled as integers.
1566 Width = Target->getIntWidth();
1567 Align = Target->getIntAlign();
1568 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001569 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001570 case BuiltinType::OCLImage1d:
1571 case BuiltinType::OCLImage1dArray:
1572 case BuiltinType::OCLImage1dBuffer:
1573 case BuiltinType::OCLImage2d:
1574 case BuiltinType::OCLImage2dArray:
1575 case BuiltinType::OCLImage3d:
1576 // Currently these types are pointers to opaque types.
1577 Width = Target->getPointerWidth(0);
1578 Align = Target->getPointerAlign(0);
1579 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001580 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001581 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001582 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001583 Width = Target->getPointerWidth(0);
1584 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001585 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001586 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001587 unsigned AS = getTargetAddressSpace(
1588 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001589 Width = Target->getPointerWidth(AS);
1590 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001591 break;
1592 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001593 case Type::LValueReference:
1594 case Type::RValueReference: {
1595 // alignof and sizeof should never enter this code path here, so we go
1596 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001597 unsigned AS = getTargetAddressSpace(
1598 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001599 Width = Target->getPointerWidth(AS);
1600 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001601 break;
1602 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001603 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001604 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001605 Width = Target->getPointerWidth(AS);
1606 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001607 break;
1608 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001609 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001610 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001611 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001612 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001613 }
Chris Lattner647fb222007-07-18 18:26:58 +00001614 case Type::Complex: {
1615 // Complex types have the same alignment as their elements, but twice the
1616 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001617 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001618 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001619 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001620 Align = EltInfo.second;
1621 break;
1622 }
John McCall8b07ec22010-05-15 11:32:37 +00001623 case Type::ObjCObject:
1624 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001625 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001626 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001627 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001628 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001629 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001630 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001631 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001632 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001633 break;
1634 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001635 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001636 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001637 const TagType *TT = cast<TagType>(T);
1638
1639 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001640 Width = 8;
1641 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001642 break;
1643 }
Mike Stump11289f42009-09-09 15:08:12 +00001644
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001645 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001646 return getTypeInfo(ET->getDecl()->getIntegerType());
1647
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001648 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001649 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001650 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001651 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001652 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001653 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001654
Chris Lattner63d2b362009-10-22 05:17:15 +00001655 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001656 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1657 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001658
Richard Smith30482bc2011-02-20 03:19:35 +00001659 case Type::Auto: {
1660 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001661 assert(!A->getDeducedType().isNull() &&
1662 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001663 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001664 }
1665
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001666 case Type::Paren:
1667 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1668
Douglas Gregoref462e62009-04-30 17:32:17 +00001669 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001670 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001671 std::pair<uint64_t, unsigned> Info
1672 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001673 // If the typedef has an aligned attribute on it, it overrides any computed
1674 // alignment we have. This violates the GCC documentation (which says that
1675 // attribute(aligned) can only round up) but matches its implementation.
1676 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1677 Align = AttrAlign;
1678 else
1679 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001680 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001681 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001682 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001683
Abramo Bagnara6150c882010-05-11 21:36:43 +00001684 case Type::Elaborated:
1685 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001686
John McCall81904512011-01-06 01:58:22 +00001687 case Type::Attributed:
1688 return getTypeInfo(
1689 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1690
Eli Friedman0dfb8892011-10-06 23:00:33 +00001691 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001692 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001693 std::pair<uint64_t, unsigned> Info
1694 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1695 Width = Info.first;
1696 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001697
1698 // If the size of the type doesn't exceed the platform's max
1699 // atomic promotion width, make the size and alignment more
1700 // favorable to atomic operations:
1701 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1702 // Round the size up to a power of 2.
1703 if (!llvm::isPowerOf2_64(Width))
1704 Width = llvm::NextPowerOf2(Width);
1705
1706 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001707 Align = static_cast<unsigned>(Width);
1708 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001709 }
1710
Douglas Gregoref462e62009-04-30 17:32:17 +00001711 }
Mike Stump11289f42009-09-09 15:08:12 +00001712
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001713 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001714 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001715}
1716
Ken Dyckcc56c542011-01-15 18:38:59 +00001717/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1718CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1719 return CharUnits::fromQuantity(BitSize / getCharWidth());
1720}
1721
Ken Dyckb0fcc592011-02-11 01:54:29 +00001722/// toBits - Convert a size in characters to a size in characters.
1723int64_t ASTContext::toBits(CharUnits CharSize) const {
1724 return CharSize.getQuantity() * getCharWidth();
1725}
1726
Ken Dyck8c89d592009-12-22 14:23:30 +00001727/// getTypeSizeInChars - Return the size of the specified type, in characters.
1728/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001729CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001730 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001731}
Jay Foad39c79802011-01-12 09:06:06 +00001732CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001733 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001734}
1735
Ken Dycka6046ab2010-01-26 17:25:18 +00001736/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001737/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001738CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001739 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001740}
Jay Foad39c79802011-01-12 09:06:06 +00001741CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001742 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001743}
1744
Chris Lattnera3402cd2009-01-27 18:08:34 +00001745/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1746/// type for the current target in bits. This can be different than the ABI
1747/// alignment in cases where it is beneficial for performance to overalign
1748/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001749unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001750 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001751
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001752 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1753 return ABIAlign; // Never overalign on XCore.
1754
David Majnemer8b6bd572014-02-24 23:34:17 +00001755 const TypedefType *TT = T->getAs<TypedefType>();
1756
Eli Friedman7ab09572009-05-25 21:27:19 +00001757 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001758 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001759 T = CT->getElementType().getTypePtr();
1760 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001761 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1762 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001763 // Don't increase the alignment if an alignment attribute was specified on a
1764 // typedef declaration.
1765 if (!TT || !TT->getDecl()->getMaxAlignment())
1766 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001767
Chris Lattnera3402cd2009-01-27 18:08:34 +00001768 return ABIAlign;
1769}
1770
Ulrich Weigandfa806422013-05-06 16:23:57 +00001771/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1772/// to a global variable of the specified type.
1773unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1774 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1775}
1776
1777/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1778/// should be given to a global variable of the specified type.
1779CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1780 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1781}
1782
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001783/// DeepCollectObjCIvars -
1784/// This routine first collects all declared, but not synthesized, ivars in
1785/// super class and then collects all ivars, including those synthesized for
1786/// current class. This routine is used for implementation of current class
1787/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001788///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001789void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1790 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001791 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001792 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1793 DeepCollectObjCIvars(SuperClass, false, Ivars);
1794 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001795 for (const auto *I : OI->ivars())
1796 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001797 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001798 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001799 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001800 Iv= Iv->getNextIvar())
1801 Ivars.push_back(Iv);
1802 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001803}
1804
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001805/// CollectInheritedProtocols - Collect all protocols in current class and
1806/// those inherited by it.
1807void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001808 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001809 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001810 // We can use protocol_iterator here instead of
1811 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001812 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001813 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001814 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001815 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001816 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001817 CollectInheritedProtocols(*P, Protocols);
1818 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001819 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001820
1821 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001822 for (const auto *Cat : OI->visible_categories())
1823 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001824
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001825 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1826 while (SD) {
1827 CollectInheritedProtocols(SD, Protocols);
1828 SD = SD->getSuperClass();
1829 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001830 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001831 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001832 PE = OC->protocol_end(); P != PE; ++P) {
1833 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001834 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001835 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1836 PE = Proto->protocol_end(); P != PE; ++P)
1837 CollectInheritedProtocols(*P, Protocols);
1838 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001839 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001840 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1841 PE = OP->protocol_end(); P != PE; ++P) {
1842 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001843 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001844 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1845 PE = Proto->protocol_end(); P != PE; ++P)
1846 CollectInheritedProtocols(*P, Protocols);
1847 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001848 }
1849}
1850
Jay Foad39c79802011-01-12 09:06:06 +00001851unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001852 unsigned count = 0;
1853 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001854 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001855 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001856
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001857 // Count ivar defined in this class's implementation. This
1858 // includes synthesized ivars.
1859 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001860 count += ImplDecl->ivar_size();
1861
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001862 return count;
1863}
1864
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001865bool ASTContext::isSentinelNullExpr(const Expr *E) {
1866 if (!E)
1867 return false;
1868
1869 // nullptr_t is always treated as null.
1870 if (E->getType()->isNullPtrType()) return true;
1871
1872 if (E->getType()->isAnyPointerType() &&
1873 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1874 Expr::NPC_ValueDependentIsNull))
1875 return true;
1876
1877 // Unfortunately, __null has type 'int'.
1878 if (isa<GNUNullExpr>(E)) return true;
1879
1880 return false;
1881}
1882
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001883/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1884ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1885 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1886 I = ObjCImpls.find(D);
1887 if (I != ObjCImpls.end())
1888 return cast<ObjCImplementationDecl>(I->second);
1889 return 0;
1890}
1891/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1892ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1893 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1894 I = ObjCImpls.find(D);
1895 if (I != ObjCImpls.end())
1896 return cast<ObjCCategoryImplDecl>(I->second);
1897 return 0;
1898}
1899
1900/// \brief Set the implementation of ObjCInterfaceDecl.
1901void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1902 ObjCImplementationDecl *ImplD) {
1903 assert(IFaceD && ImplD && "Passed null params");
1904 ObjCImpls[IFaceD] = ImplD;
1905}
1906/// \brief Set the implementation of ObjCCategoryDecl.
1907void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1908 ObjCCategoryImplDecl *ImplD) {
1909 assert(CatD && ImplD && "Passed null params");
1910 ObjCImpls[CatD] = ImplD;
1911}
1912
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001913const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1914 const NamedDecl *ND) const {
1915 if (const ObjCInterfaceDecl *ID =
1916 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001917 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001918 if (const ObjCCategoryDecl *CD =
1919 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001920 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001921 if (const ObjCImplDecl *IMD =
1922 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001923 return IMD->getClassInterface();
1924
1925 return 0;
1926}
1927
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001928/// \brief Get the copy initialization expression of VarDecl,or NULL if
1929/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001930Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001931 assert(VD && "Passed null params");
1932 assert(VD->hasAttr<BlocksAttr>() &&
1933 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001934 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001935 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001936 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1937}
1938
1939/// \brief Set the copy inialization expression of a block var decl.
1940void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1941 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001942 assert(VD->hasAttr<BlocksAttr>() &&
1943 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001944 BlockVarCopyInits[VD] = Init;
1945}
1946
John McCallbcd03502009-12-07 02:54:59 +00001947TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001948 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001949 if (!DataSize)
1950 DataSize = TypeLoc::getFullDataSizeForType(T);
1951 else
1952 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001953 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001954
John McCallbcd03502009-12-07 02:54:59 +00001955 TypeSourceInfo *TInfo =
1956 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1957 new (TInfo) TypeSourceInfo(T);
1958 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001959}
1960
John McCallbcd03502009-12-07 02:54:59 +00001961TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001962 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001963 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001964 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001965 return DI;
1966}
1967
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001968const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001969ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001970 return getObjCLayout(D, 0);
1971}
1972
1973const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001974ASTContext::getASTObjCImplementationLayout(
1975 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001976 return getObjCLayout(D->getClassInterface(), D);
1977}
1978
Chris Lattner983a8bb2007-07-13 22:13:22 +00001979//===----------------------------------------------------------------------===//
1980// Type creation/memoization methods
1981//===----------------------------------------------------------------------===//
1982
Jay Foad39c79802011-01-12 09:06:06 +00001983QualType
John McCall33ddac02011-01-19 10:06:00 +00001984ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1985 unsigned fastQuals = quals.getFastQualifiers();
1986 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001987
1988 // Check if we've already instantiated this type.
1989 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001990 ExtQuals::Profile(ID, baseType, quals);
1991 void *insertPos = 0;
1992 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1993 assert(eq->getQualifiers() == quals);
1994 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001995 }
1996
John McCall33ddac02011-01-19 10:06:00 +00001997 // If the base type is not canonical, make the appropriate canonical type.
1998 QualType canon;
1999 if (!baseType->isCanonicalUnqualified()) {
2000 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002001 canonSplit.Quals.addConsistentQualifiers(quals);
2002 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002003
2004 // Re-find the insert position.
2005 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2006 }
2007
2008 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2009 ExtQualNodes.InsertNode(eq, insertPos);
2010 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002011}
2012
Jay Foad39c79802011-01-12 09:06:06 +00002013QualType
2014ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002015 QualType CanT = getCanonicalType(T);
2016 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002017 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002018
John McCall8ccfcb52009-09-24 19:53:00 +00002019 // If we are composing extended qualifiers together, merge together
2020 // into one ExtQuals node.
2021 QualifierCollector Quals;
2022 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002023
John McCall8ccfcb52009-09-24 19:53:00 +00002024 // If this type already has an address space specified, it cannot get
2025 // another one.
2026 assert(!Quals.hasAddressSpace() &&
2027 "Type cannot be in multiple addr spaces!");
2028 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002029
John McCall8ccfcb52009-09-24 19:53:00 +00002030 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002031}
2032
Chris Lattnerd60183d2009-02-18 22:53:11 +00002033QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002034 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002035 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002036 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002037 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002038
John McCall53fa7142010-12-24 02:08:15 +00002039 if (const PointerType *ptr = T->getAs<PointerType>()) {
2040 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002041 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002042 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2043 return getPointerType(ResultType);
2044 }
2045 }
Mike Stump11289f42009-09-09 15:08:12 +00002046
John McCall8ccfcb52009-09-24 19:53:00 +00002047 // If we are composing extended qualifiers together, merge together
2048 // into one ExtQuals node.
2049 QualifierCollector Quals;
2050 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002051
John McCall8ccfcb52009-09-24 19:53:00 +00002052 // If this type already has an ObjCGC specified, it cannot get
2053 // another one.
2054 assert(!Quals.hasObjCGCAttr() &&
2055 "Type cannot have multiple ObjCGCs!");
2056 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002057
John McCall8ccfcb52009-09-24 19:53:00 +00002058 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002059}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002060
John McCall4f5019e2010-12-19 02:44:49 +00002061const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2062 FunctionType::ExtInfo Info) {
2063 if (T->getExtInfo() == Info)
2064 return T;
2065
2066 QualType Result;
2067 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002068 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002069 } else {
2070 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2071 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2072 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002073 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002074 }
2075
2076 return cast<FunctionType>(Result.getTypePtr());
2077}
2078
Richard Smith2a7d4812013-05-04 07:00:32 +00002079void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2080 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002081 FD = FD->getMostRecentDecl();
2082 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002083 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2084 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002085 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002086 if (FunctionDecl *Next = FD->getPreviousDecl())
2087 FD = Next;
2088 else
2089 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002090 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002091 if (ASTMutationListener *L = getASTMutationListener())
2092 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002093}
2094
Chris Lattnerc6395932007-06-22 20:56:16 +00002095/// getComplexType - Return the uniqued reference to the type for a complex
2096/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002097QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002098 // Unique pointers, to guarantee there is only one pointer of a particular
2099 // structure.
2100 llvm::FoldingSetNodeID ID;
2101 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002102
Chris Lattnerc6395932007-06-22 20:56:16 +00002103 void *InsertPos = 0;
2104 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2105 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002106
Chris Lattnerc6395932007-06-22 20:56:16 +00002107 // If the pointee type isn't canonical, this won't be a canonical type either,
2108 // so fill in the canonical type field.
2109 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002110 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002111 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002112
Chris Lattnerc6395932007-06-22 20:56:16 +00002113 // Get the new insert position for the node we care about.
2114 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002115 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002116 }
John McCall90d1c2d2009-09-24 23:30:46 +00002117 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002118 Types.push_back(New);
2119 ComplexTypes.InsertNode(New, InsertPos);
2120 return QualType(New, 0);
2121}
2122
Chris Lattner970e54e2006-11-12 00:37:36 +00002123/// getPointerType - Return the uniqued reference to the type for a pointer to
2124/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002125QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002126 // Unique pointers, to guarantee there is only one pointer of a particular
2127 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002128 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002129 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002130
Chris Lattner67521df2007-01-27 01:29:36 +00002131 void *InsertPos = 0;
2132 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002133 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002134
Chris Lattner7ccecb92006-11-12 08:50:50 +00002135 // If the pointee type isn't canonical, this won't be a canonical type either,
2136 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002137 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002138 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002139 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002140
Bob Wilsonc8541f22013-03-15 17:12:43 +00002141 // Get the new insert position for the node we care about.
2142 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2143 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2144 }
John McCall90d1c2d2009-09-24 23:30:46 +00002145 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002146 Types.push_back(New);
2147 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002148 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002149}
2150
Reid Kleckner0503a872013-12-05 01:23:43 +00002151QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2152 llvm::FoldingSetNodeID ID;
2153 AdjustedType::Profile(ID, Orig, New);
2154 void *InsertPos = 0;
2155 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2156 if (AT)
2157 return QualType(AT, 0);
2158
2159 QualType Canonical = getCanonicalType(New);
2160
2161 // Get the new insert position for the node we care about.
2162 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2163 assert(AT == 0 && "Shouldn't be in the map!");
2164
2165 AT = new (*this, TypeAlignment)
2166 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2167 Types.push_back(AT);
2168 AdjustedTypes.InsertNode(AT, InsertPos);
2169 return QualType(AT, 0);
2170}
2171
Reid Kleckner8a365022013-06-24 17:51:48 +00002172QualType ASTContext::getDecayedType(QualType T) const {
2173 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2174
Reid Kleckner8a365022013-06-24 17:51:48 +00002175 QualType Decayed;
2176
2177 // C99 6.7.5.3p7:
2178 // A declaration of a parameter as "array of type" shall be
2179 // adjusted to "qualified pointer to type", where the type
2180 // qualifiers (if any) are those specified within the [ and ] of
2181 // the array type derivation.
2182 if (T->isArrayType())
2183 Decayed = getArrayDecayedType(T);
2184
2185 // C99 6.7.5.3p8:
2186 // A declaration of a parameter as "function returning type"
2187 // shall be adjusted to "pointer to function returning type", as
2188 // in 6.3.2.1.
2189 if (T->isFunctionType())
2190 Decayed = getPointerType(T);
2191
Reid Kleckner0503a872013-12-05 01:23:43 +00002192 llvm::FoldingSetNodeID ID;
2193 AdjustedType::Profile(ID, T, Decayed);
2194 void *InsertPos = 0;
2195 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2196 if (AT)
2197 return QualType(AT, 0);
2198
Reid Kleckner8a365022013-06-24 17:51:48 +00002199 QualType Canonical = getCanonicalType(Decayed);
2200
2201 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002202 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2203 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002204
Reid Kleckner0503a872013-12-05 01:23:43 +00002205 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2206 Types.push_back(AT);
2207 AdjustedTypes.InsertNode(AT, InsertPos);
2208 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002209}
2210
Mike Stump11289f42009-09-09 15:08:12 +00002211/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002212/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002213QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002214 assert(T->isFunctionType() && "block of function types only");
2215 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002216 // structure.
2217 llvm::FoldingSetNodeID ID;
2218 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002219
Steve Naroffec33ed92008-08-27 16:04:49 +00002220 void *InsertPos = 0;
2221 if (BlockPointerType *PT =
2222 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2223 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002224
2225 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002226 // type either so fill in the canonical type field.
2227 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002228 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002229 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002230
Steve Naroffec33ed92008-08-27 16:04:49 +00002231 // Get the new insert position for the node we care about.
2232 BlockPointerType *NewIP =
2233 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002234 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002235 }
John McCall90d1c2d2009-09-24 23:30:46 +00002236 BlockPointerType *New
2237 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002238 Types.push_back(New);
2239 BlockPointerTypes.InsertNode(New, InsertPos);
2240 return QualType(New, 0);
2241}
2242
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002243/// getLValueReferenceType - Return the uniqued reference to the type for an
2244/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002245QualType
2246ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002247 assert(getCanonicalType(T) != OverloadTy &&
2248 "Unresolved overloaded function type");
2249
Bill Wendling3708c182007-05-27 10:15:43 +00002250 // Unique pointers, to guarantee there is only one pointer of a particular
2251 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002252 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002253 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002254
2255 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002256 if (LValueReferenceType *RT =
2257 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002258 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002259
John McCallfc93cf92009-10-22 22:37:11 +00002260 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2261
Bill Wendling3708c182007-05-27 10:15:43 +00002262 // If the referencee type isn't canonical, this won't be a canonical type
2263 // either, so fill in the canonical type field.
2264 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002265 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2266 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2267 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002268
Bill Wendling3708c182007-05-27 10:15:43 +00002269 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002270 LValueReferenceType *NewIP =
2271 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002272 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002273 }
2274
John McCall90d1c2d2009-09-24 23:30:46 +00002275 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002276 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2277 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002278 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002279 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002280
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002281 return QualType(New, 0);
2282}
2283
2284/// getRValueReferenceType - Return the uniqued reference to the type for an
2285/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002286QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002287 // Unique pointers, to guarantee there is only one pointer of a particular
2288 // structure.
2289 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002290 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002291
2292 void *InsertPos = 0;
2293 if (RValueReferenceType *RT =
2294 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2295 return QualType(RT, 0);
2296
John McCallfc93cf92009-10-22 22:37:11 +00002297 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2298
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002299 // If the referencee type isn't canonical, this won't be a canonical type
2300 // either, so fill in the canonical type field.
2301 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002302 if (InnerRef || !T.isCanonical()) {
2303 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2304 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002305
2306 // Get the new insert position for the node we care about.
2307 RValueReferenceType *NewIP =
2308 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002309 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002310 }
2311
John McCall90d1c2d2009-09-24 23:30:46 +00002312 RValueReferenceType *New
2313 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002314 Types.push_back(New);
2315 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002316 return QualType(New, 0);
2317}
2318
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002319/// getMemberPointerType - Return the uniqued reference to the type for a
2320/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002321QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002322 // Unique pointers, to guarantee there is only one pointer of a particular
2323 // structure.
2324 llvm::FoldingSetNodeID ID;
2325 MemberPointerType::Profile(ID, T, Cls);
2326
2327 void *InsertPos = 0;
2328 if (MemberPointerType *PT =
2329 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2330 return QualType(PT, 0);
2331
2332 // If the pointee or class type isn't canonical, this won't be a canonical
2333 // type either, so fill in the canonical type field.
2334 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002335 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002336 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2337
2338 // Get the new insert position for the node we care about.
2339 MemberPointerType *NewIP =
2340 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002341 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002342 }
John McCall90d1c2d2009-09-24 23:30:46 +00002343 MemberPointerType *New
2344 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002345 Types.push_back(New);
2346 MemberPointerTypes.InsertNode(New, InsertPos);
2347 return QualType(New, 0);
2348}
2349
Mike Stump11289f42009-09-09 15:08:12 +00002350/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002351/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002352QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002353 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002354 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002355 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002356 assert((EltTy->isDependentType() ||
2357 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002358 "Constant array of VLAs is illegal!");
2359
Chris Lattnere2df3f92009-05-13 04:12:56 +00002360 // Convert the array size into a canonical width matching the pointer size for
2361 // the target.
2362 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002363 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002364 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002365
Chris Lattner23b7eb62007-06-15 23:05:46 +00002366 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002367 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002368
Chris Lattner36f8e652007-01-27 08:31:04 +00002369 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002370 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002371 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002372 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002373
John McCall33ddac02011-01-19 10:06:00 +00002374 // If the element type isn't canonical or has qualifiers, this won't
2375 // be a canonical type either, so fill in the canonical type field.
2376 QualType Canon;
2377 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2378 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002379 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002380 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002381 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002382
Chris Lattner36f8e652007-01-27 08:31:04 +00002383 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002384 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002385 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002386 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002387 }
Mike Stump11289f42009-09-09 15:08:12 +00002388
John McCall90d1c2d2009-09-24 23:30:46 +00002389 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002390 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002391 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002392 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002393 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002394}
2395
John McCall06549462011-01-18 08:40:38 +00002396/// getVariableArrayDecayedType - Turns the given type, which may be
2397/// variably-modified, into the corresponding type with all the known
2398/// sizes replaced with [*].
2399QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2400 // Vastly most common case.
2401 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002402
John McCall06549462011-01-18 08:40:38 +00002403 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002404
John McCall06549462011-01-18 08:40:38 +00002405 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002406 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002407 switch (ty->getTypeClass()) {
2408#define TYPE(Class, Base)
2409#define ABSTRACT_TYPE(Class, Base)
2410#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2411#include "clang/AST/TypeNodes.def"
2412 llvm_unreachable("didn't desugar past all non-canonical types?");
2413
2414 // These types should never be variably-modified.
2415 case Type::Builtin:
2416 case Type::Complex:
2417 case Type::Vector:
2418 case Type::ExtVector:
2419 case Type::DependentSizedExtVector:
2420 case Type::ObjCObject:
2421 case Type::ObjCInterface:
2422 case Type::ObjCObjectPointer:
2423 case Type::Record:
2424 case Type::Enum:
2425 case Type::UnresolvedUsing:
2426 case Type::TypeOfExpr:
2427 case Type::TypeOf:
2428 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002429 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002430 case Type::DependentName:
2431 case Type::InjectedClassName:
2432 case Type::TemplateSpecialization:
2433 case Type::DependentTemplateSpecialization:
2434 case Type::TemplateTypeParm:
2435 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002436 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002437 case Type::PackExpansion:
2438 llvm_unreachable("type should never be variably-modified");
2439
2440 // These types can be variably-modified but should never need to
2441 // further decay.
2442 case Type::FunctionNoProto:
2443 case Type::FunctionProto:
2444 case Type::BlockPointer:
2445 case Type::MemberPointer:
2446 return type;
2447
2448 // These types can be variably-modified. All these modifications
2449 // preserve structure except as noted by comments.
2450 // TODO: if we ever care about optimizing VLAs, there are no-op
2451 // optimizations available here.
2452 case Type::Pointer:
2453 result = getPointerType(getVariableArrayDecayedType(
2454 cast<PointerType>(ty)->getPointeeType()));
2455 break;
2456
2457 case Type::LValueReference: {
2458 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2459 result = getLValueReferenceType(
2460 getVariableArrayDecayedType(lv->getPointeeType()),
2461 lv->isSpelledAsLValue());
2462 break;
2463 }
2464
2465 case Type::RValueReference: {
2466 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2467 result = getRValueReferenceType(
2468 getVariableArrayDecayedType(lv->getPointeeType()));
2469 break;
2470 }
2471
Eli Friedman0dfb8892011-10-06 23:00:33 +00002472 case Type::Atomic: {
2473 const AtomicType *at = cast<AtomicType>(ty);
2474 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2475 break;
2476 }
2477
John McCall06549462011-01-18 08:40:38 +00002478 case Type::ConstantArray: {
2479 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2480 result = getConstantArrayType(
2481 getVariableArrayDecayedType(cat->getElementType()),
2482 cat->getSize(),
2483 cat->getSizeModifier(),
2484 cat->getIndexTypeCVRQualifiers());
2485 break;
2486 }
2487
2488 case Type::DependentSizedArray: {
2489 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2490 result = getDependentSizedArrayType(
2491 getVariableArrayDecayedType(dat->getElementType()),
2492 dat->getSizeExpr(),
2493 dat->getSizeModifier(),
2494 dat->getIndexTypeCVRQualifiers(),
2495 dat->getBracketsRange());
2496 break;
2497 }
2498
2499 // Turn incomplete types into [*] types.
2500 case Type::IncompleteArray: {
2501 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2502 result = getVariableArrayType(
2503 getVariableArrayDecayedType(iat->getElementType()),
2504 /*size*/ 0,
2505 ArrayType::Normal,
2506 iat->getIndexTypeCVRQualifiers(),
2507 SourceRange());
2508 break;
2509 }
2510
2511 // Turn VLA types into [*] types.
2512 case Type::VariableArray: {
2513 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2514 result = getVariableArrayType(
2515 getVariableArrayDecayedType(vat->getElementType()),
2516 /*size*/ 0,
2517 ArrayType::Star,
2518 vat->getIndexTypeCVRQualifiers(),
2519 vat->getBracketsRange());
2520 break;
2521 }
2522 }
2523
2524 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002525 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002526}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002527
Steve Naroffcadebd02007-08-30 18:14:25 +00002528/// getVariableArrayType - Returns a non-unique reference to the type for a
2529/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002530QualType ASTContext::getVariableArrayType(QualType EltTy,
2531 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002532 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002533 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002534 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002535 // Since we don't unique expressions, it isn't possible to unique VLA's
2536 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002537 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002538
John McCall33ddac02011-01-19 10:06:00 +00002539 // Be sure to pull qualifiers off the element type.
2540 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2541 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002542 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002543 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002544 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002545 }
2546
John McCall90d1c2d2009-09-24 23:30:46 +00002547 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002548 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002549
2550 VariableArrayTypes.push_back(New);
2551 Types.push_back(New);
2552 return QualType(New, 0);
2553}
2554
Douglas Gregor4619e432008-12-05 23:32:09 +00002555/// getDependentSizedArrayType - Returns a non-unique reference to
2556/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002557/// type.
John McCall33ddac02011-01-19 10:06:00 +00002558QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2559 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002560 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002561 unsigned elementTypeQuals,
2562 SourceRange brackets) const {
2563 assert((!numElements || numElements->isTypeDependent() ||
2564 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002565 "Size must be type- or value-dependent!");
2566
John McCall33ddac02011-01-19 10:06:00 +00002567 // Dependently-sized array types that do not have a specified number
2568 // of elements will have their sizes deduced from a dependent
2569 // initializer. We do no canonicalization here at all, which is okay
2570 // because they can't be used in most locations.
2571 if (!numElements) {
2572 DependentSizedArrayType *newType
2573 = new (*this, TypeAlignment)
2574 DependentSizedArrayType(*this, elementType, QualType(),
2575 numElements, ASM, elementTypeQuals,
2576 brackets);
2577 Types.push_back(newType);
2578 return QualType(newType, 0);
2579 }
2580
2581 // Otherwise, we actually build a new type every time, but we
2582 // also build a canonical type.
2583
2584 SplitQualType canonElementType = getCanonicalType(elementType).split();
2585
2586 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002587 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002588 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002589 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002590 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002591
John McCall33ddac02011-01-19 10:06:00 +00002592 // Look for an existing type with these properties.
2593 DependentSizedArrayType *canonTy =
2594 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002595
John McCall33ddac02011-01-19 10:06:00 +00002596 // If we don't have one, build one.
2597 if (!canonTy) {
2598 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002599 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002600 QualType(), numElements, ASM, elementTypeQuals,
2601 brackets);
2602 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2603 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002604 }
2605
John McCall33ddac02011-01-19 10:06:00 +00002606 // Apply qualifiers from the element type to the array.
2607 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002608 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002609
John McCall33ddac02011-01-19 10:06:00 +00002610 // If we didn't need extra canonicalization for the element type,
2611 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002612 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002613 return canon;
2614
2615 // Otherwise, we need to build a type which follows the spelling
2616 // of the element type.
2617 DependentSizedArrayType *sugaredType
2618 = new (*this, TypeAlignment)
2619 DependentSizedArrayType(*this, elementType, canon, numElements,
2620 ASM, elementTypeQuals, brackets);
2621 Types.push_back(sugaredType);
2622 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002623}
2624
John McCall33ddac02011-01-19 10:06:00 +00002625QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002626 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002627 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002628 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002629 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002630
John McCall33ddac02011-01-19 10:06:00 +00002631 void *insertPos = 0;
2632 if (IncompleteArrayType *iat =
2633 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2634 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002635
2636 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002637 // either, so fill in the canonical type field. We also have to pull
2638 // qualifiers off the element type.
2639 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002640
John McCall33ddac02011-01-19 10:06:00 +00002641 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2642 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002643 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002644 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002645 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002646
2647 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002648 IncompleteArrayType *existing =
2649 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2650 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002651 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002652
John McCall33ddac02011-01-19 10:06:00 +00002653 IncompleteArrayType *newType = new (*this, TypeAlignment)
2654 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002655
John McCall33ddac02011-01-19 10:06:00 +00002656 IncompleteArrayTypes.InsertNode(newType, insertPos);
2657 Types.push_back(newType);
2658 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002659}
2660
Steve Naroff91fcddb2007-07-18 18:00:27 +00002661/// getVectorType - Return the unique reference to a vector type of
2662/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002663QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002664 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002665 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002666
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002667 // Check if we've already instantiated a vector of this type.
2668 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002669 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002670
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002671 void *InsertPos = 0;
2672 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2673 return QualType(VTP, 0);
2674
2675 // If the element type isn't canonical, this won't be a canonical type either,
2676 // so fill in the canonical type field.
2677 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002678 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002679 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002680
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002681 // Get the new insert position for the node we care about.
2682 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002683 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002684 }
John McCall90d1c2d2009-09-24 23:30:46 +00002685 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002686 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002687 VectorTypes.InsertNode(New, InsertPos);
2688 Types.push_back(New);
2689 return QualType(New, 0);
2690}
2691
Nate Begemance4d7fc2008-04-18 23:10:10 +00002692/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002693/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002694QualType
2695ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002696 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002697
Steve Naroff91fcddb2007-07-18 18:00:27 +00002698 // Check if we've already instantiated a vector of this type.
2699 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002700 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002701 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002702 void *InsertPos = 0;
2703 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2704 return QualType(VTP, 0);
2705
2706 // If the element type isn't canonical, this won't be a canonical type either,
2707 // so fill in the canonical type field.
2708 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002709 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002710 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002711
Steve Naroff91fcddb2007-07-18 18:00:27 +00002712 // Get the new insert position for the node we care about.
2713 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002714 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002715 }
John McCall90d1c2d2009-09-24 23:30:46 +00002716 ExtVectorType *New = new (*this, TypeAlignment)
2717 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002718 VectorTypes.InsertNode(New, InsertPos);
2719 Types.push_back(New);
2720 return QualType(New, 0);
2721}
2722
Jay Foad39c79802011-01-12 09:06:06 +00002723QualType
2724ASTContext::getDependentSizedExtVectorType(QualType vecType,
2725 Expr *SizeExpr,
2726 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002727 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002728 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002729 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002730
Douglas Gregor352169a2009-07-31 03:54:25 +00002731 void *InsertPos = 0;
2732 DependentSizedExtVectorType *Canon
2733 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2734 DependentSizedExtVectorType *New;
2735 if (Canon) {
2736 // We already have a canonical version of this array type; use it as
2737 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002738 New = new (*this, TypeAlignment)
2739 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2740 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002741 } else {
2742 QualType CanonVecTy = getCanonicalType(vecType);
2743 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002744 New = new (*this, TypeAlignment)
2745 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2746 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002747
2748 DependentSizedExtVectorType *CanonCheck
2749 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2750 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2751 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002752 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2753 } else {
2754 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2755 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002756 New = new (*this, TypeAlignment)
2757 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002758 }
2759 }
Mike Stump11289f42009-09-09 15:08:12 +00002760
Douglas Gregor758a8692009-06-17 21:51:59 +00002761 Types.push_back(New);
2762 return QualType(New, 0);
2763}
2764
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002765/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002766///
Jay Foad39c79802011-01-12 09:06:06 +00002767QualType
2768ASTContext::getFunctionNoProtoType(QualType ResultTy,
2769 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002770 const CallingConv CallConv = Info.getCC();
2771
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002772 // Unique functions, to guarantee there is only one function of a particular
2773 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002774 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002775 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002776
Chris Lattner47955de2007-01-27 08:37:20 +00002777 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002778 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002779 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002780 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002781
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002782 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002783 if (!ResultTy.isCanonical()) {
2784 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002785
Chris Lattner47955de2007-01-27 08:37:20 +00002786 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002787 FunctionNoProtoType *NewIP =
2788 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002789 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002790 }
Mike Stump11289f42009-09-09 15:08:12 +00002791
Roman Divacky65b88cd2011-03-01 17:40:53 +00002792 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002793 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002794 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002795 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002796 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002797 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002798}
2799
Douglas Gregorcd780372013-01-17 23:36:45 +00002800/// \brief Determine whether \p T is canonical as the result type of a function.
2801static bool isCanonicalResultType(QualType T) {
2802 return T.isCanonical() &&
2803 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2804 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2805}
2806
Jay Foad39c79802011-01-12 09:06:06 +00002807QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002808ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002809 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002810 size_t NumArgs = ArgArray.size();
2811
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002812 // Unique functions, to guarantee there is only one function of a particular
2813 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002814 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002815 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2816 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002817
2818 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002819 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002820 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002821 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002822
2823 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002824 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002825 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002826 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002827 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002828 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002829 isCanonical = false;
2830
2831 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002832 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002833 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002834 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002835 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002836 CanonicalArgs.reserve(NumArgs);
2837 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002838 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002839
John McCalldb40c7f2010-12-14 08:05:40 +00002840 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002841 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002842 CanonicalEPI.ExceptionSpecType = EST_None;
2843 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002844
Douglas Gregorcd780372013-01-17 23:36:45 +00002845 // Result types do not have ARC lifetime qualifiers.
2846 QualType CanResultTy = getCanonicalType(ResultTy);
2847 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2848 Qualifiers Qs = CanResultTy.getQualifiers();
2849 Qs.removeObjCLifetime();
2850 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2851 }
2852
Jordan Rose5c382722013-03-08 21:51:21 +00002853 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002854
Chris Lattnerfd4de792007-01-27 01:15:32 +00002855 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002856 FunctionProtoType *NewIP =
2857 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002858 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002859 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002860
John McCall31168b02011-06-15 23:02:42 +00002861 // FunctionProtoType objects are allocated with extra bytes after
2862 // them for three variable size arrays at the end:
2863 // - parameter types
2864 // - exception types
2865 // - consumed-arguments flags
2866 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002867 // expression, or information used to resolve the exception
2868 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002869 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002870 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002871 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002872 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002873 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002874 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002875 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002876 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002877 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2878 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002879 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002880 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002881 Size += NumArgs * sizeof(bool);
2882
John McCalldb40c7f2010-12-14 08:05:40 +00002883 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002884 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002885 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002886 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002887 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002888 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002889}
Chris Lattneref51c202006-11-10 07:17:23 +00002890
John McCalle78aac42010-03-10 03:28:59 +00002891#ifndef NDEBUG
2892static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2893 if (!isa<CXXRecordDecl>(D)) return false;
2894 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2895 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2896 return true;
2897 if (RD->getDescribedClassTemplate() &&
2898 !isa<ClassTemplateSpecializationDecl>(RD))
2899 return true;
2900 return false;
2901}
2902#endif
2903
2904/// getInjectedClassNameType - Return the unique reference to the
2905/// injected class name type for the specified templated declaration.
2906QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002907 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002908 assert(NeedsInjectedClassNameType(Decl));
2909 if (Decl->TypeForDecl) {
2910 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002911 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002912 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2913 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2914 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2915 } else {
John McCall424cec92011-01-19 06:33:43 +00002916 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002917 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002918 Decl->TypeForDecl = newType;
2919 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002920 }
2921 return QualType(Decl->TypeForDecl, 0);
2922}
2923
Douglas Gregor83a586e2008-04-13 21:07:44 +00002924/// getTypeDeclType - Return the unique reference to the type for the
2925/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002926QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002927 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002928 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002929
Richard Smithdda56e42011-04-15 14:24:37 +00002930 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002931 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002932
John McCall96f0b5f2010-03-10 06:48:02 +00002933 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2934 "Template type parameter types are always available.");
2935
John McCall81e38502010-02-16 03:57:14 +00002936 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002937 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002938 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002939 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002940 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002941 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002942 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002943 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002944 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002945 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2946 Decl->TypeForDecl = newType;
2947 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002948 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002949 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002950
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002951 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002952}
2953
Chris Lattner32d920b2007-01-26 02:01:53 +00002954/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002955/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002956QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002957ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2958 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002959 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002960
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002961 if (Canonical.isNull())
2962 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002963 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002964 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002965 Decl->TypeForDecl = newType;
2966 Types.push_back(newType);
2967 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002968}
2969
Jay Foad39c79802011-01-12 09:06:06 +00002970QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002971 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2972
Douglas Gregorec9fd132012-01-14 16:38:05 +00002973 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002974 if (PrevDecl->TypeForDecl)
2975 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2976
John McCall424cec92011-01-19 06:33:43 +00002977 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2978 Decl->TypeForDecl = newType;
2979 Types.push_back(newType);
2980 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002981}
2982
Jay Foad39c79802011-01-12 09:06:06 +00002983QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002984 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2985
Douglas Gregorec9fd132012-01-14 16:38:05 +00002986 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002987 if (PrevDecl->TypeForDecl)
2988 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2989
John McCall424cec92011-01-19 06:33:43 +00002990 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2991 Decl->TypeForDecl = newType;
2992 Types.push_back(newType);
2993 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002994}
2995
John McCall81904512011-01-06 01:58:22 +00002996QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2997 QualType modifiedType,
2998 QualType equivalentType) {
2999 llvm::FoldingSetNodeID id;
3000 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3001
3002 void *insertPos = 0;
3003 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3004 if (type) return QualType(type, 0);
3005
3006 QualType canon = getCanonicalType(equivalentType);
3007 type = new (*this, TypeAlignment)
3008 AttributedType(canon, attrKind, modifiedType, equivalentType);
3009
3010 Types.push_back(type);
3011 AttributedTypes.InsertNode(type, insertPos);
3012
3013 return QualType(type, 0);
3014}
3015
3016
John McCallcebee162009-10-18 09:09:24 +00003017/// \brief Retrieve a substitution-result type.
3018QualType
3019ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003020 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003021 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003022 && "replacement types must always be canonical");
3023
3024 llvm::FoldingSetNodeID ID;
3025 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3026 void *InsertPos = 0;
3027 SubstTemplateTypeParmType *SubstParm
3028 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3029
3030 if (!SubstParm) {
3031 SubstParm = new (*this, TypeAlignment)
3032 SubstTemplateTypeParmType(Parm, Replacement);
3033 Types.push_back(SubstParm);
3034 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3035 }
3036
3037 return QualType(SubstParm, 0);
3038}
3039
Douglas Gregorada4b792011-01-14 02:55:32 +00003040/// \brief Retrieve a
3041QualType ASTContext::getSubstTemplateTypeParmPackType(
3042 const TemplateTypeParmType *Parm,
3043 const TemplateArgument &ArgPack) {
3044#ifndef NDEBUG
3045 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3046 PEnd = ArgPack.pack_end();
3047 P != PEnd; ++P) {
3048 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3049 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3050 }
3051#endif
3052
3053 llvm::FoldingSetNodeID ID;
3054 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3055 void *InsertPos = 0;
3056 if (SubstTemplateTypeParmPackType *SubstParm
3057 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3058 return QualType(SubstParm, 0);
3059
3060 QualType Canon;
3061 if (!Parm->isCanonicalUnqualified()) {
3062 Canon = getCanonicalType(QualType(Parm, 0));
3063 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3064 ArgPack);
3065 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3066 }
3067
3068 SubstTemplateTypeParmPackType *SubstParm
3069 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3070 ArgPack);
3071 Types.push_back(SubstParm);
3072 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3073 return QualType(SubstParm, 0);
3074}
3075
Douglas Gregoreff93e02009-02-05 23:33:38 +00003076/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003077/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003078/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003079QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003080 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003081 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003082 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003083 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003084 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003085 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003086 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3087
3088 if (TypeParm)
3089 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003090
Chandler Carruth08836322011-05-01 00:51:33 +00003091 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003092 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003093 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003094
3095 TemplateTypeParmType *TypeCheck
3096 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3097 assert(!TypeCheck && "Template type parameter canonical type broken");
3098 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003099 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003100 TypeParm = new (*this, TypeAlignment)
3101 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003102
3103 Types.push_back(TypeParm);
3104 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3105
3106 return QualType(TypeParm, 0);
3107}
3108
John McCalle78aac42010-03-10 03:28:59 +00003109TypeSourceInfo *
3110ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3111 SourceLocation NameLoc,
3112 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003113 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003114 assert(!Name.getAsDependentTemplateName() &&
3115 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003116 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003117
3118 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003119 TemplateSpecializationTypeLoc TL =
3120 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003121 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003122 TL.setTemplateNameLoc(NameLoc);
3123 TL.setLAngleLoc(Args.getLAngleLoc());
3124 TL.setRAngleLoc(Args.getRAngleLoc());
3125 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3126 TL.setArgLocInfo(i, Args[i].getLocInfo());
3127 return DI;
3128}
3129
Mike Stump11289f42009-09-09 15:08:12 +00003130QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003131ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003132 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003133 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003134 assert(!Template.getAsDependentTemplateName() &&
3135 "No dependent template names here!");
3136
John McCall6b51f282009-11-23 01:53:49 +00003137 unsigned NumArgs = Args.size();
3138
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003139 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003140 ArgVec.reserve(NumArgs);
3141 for (unsigned i = 0; i != NumArgs; ++i)
3142 ArgVec.push_back(Args[i].getArgument());
3143
John McCall2408e322010-04-27 00:57:59 +00003144 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003145 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003146}
3147
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003148#ifndef NDEBUG
3149static bool hasAnyPackExpansions(const TemplateArgument *Args,
3150 unsigned NumArgs) {
3151 for (unsigned I = 0; I != NumArgs; ++I)
3152 if (Args[I].isPackExpansion())
3153 return true;
3154
3155 return true;
3156}
3157#endif
3158
John McCall0ad16662009-10-29 08:12:44 +00003159QualType
3160ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003161 const TemplateArgument *Args,
3162 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003163 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003164 assert(!Template.getAsDependentTemplateName() &&
3165 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003166 // Look through qualified template names.
3167 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3168 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003169
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003170 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003171 Template.getAsTemplateDecl() &&
3172 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003173 QualType CanonType;
3174 if (!Underlying.isNull())
3175 CanonType = getCanonicalType(Underlying);
3176 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003177 // We can get here with an alias template when the specialization contains
3178 // a pack expansion that does not match up with a parameter pack.
3179 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3180 "Caller must compute aliased type");
3181 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003182 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3183 NumArgs);
3184 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003185
Douglas Gregora8e02e72009-07-28 23:00:59 +00003186 // Allocate the (non-canonical) template specialization type, but don't
3187 // try to unique it: these types typically have location information that
3188 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003189 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3190 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003191 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003192 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003193 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003194 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3195 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003196
Douglas Gregor8bf42052009-02-09 18:46:07 +00003197 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003198 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003199}
3200
Mike Stump11289f42009-09-09 15:08:12 +00003201QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003202ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3203 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003204 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003205 assert(!Template.getAsDependentTemplateName() &&
3206 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003207
Douglas Gregore29139c2011-03-03 17:04:51 +00003208 // Look through qualified template names.
3209 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3210 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003211
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003212 // Build the canonical template specialization type.
3213 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003214 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003215 CanonArgs.reserve(NumArgs);
3216 for (unsigned I = 0; I != NumArgs; ++I)
3217 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3218
3219 // Determine whether this canonical template specialization type already
3220 // exists.
3221 llvm::FoldingSetNodeID ID;
3222 TemplateSpecializationType::Profile(ID, CanonTemplate,
3223 CanonArgs.data(), NumArgs, *this);
3224
3225 void *InsertPos = 0;
3226 TemplateSpecializationType *Spec
3227 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3228
3229 if (!Spec) {
3230 // Allocate a new canonical template specialization type.
3231 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3232 sizeof(TemplateArgument) * NumArgs),
3233 TypeAlignment);
3234 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3235 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003236 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003237 Types.push_back(Spec);
3238 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3239 }
3240
3241 assert(Spec->isDependentType() &&
3242 "Non-dependent template-id type must have a canonical type");
3243 return QualType(Spec, 0);
3244}
3245
3246QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003247ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3248 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003249 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003250 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003251 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003252
3253 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003254 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003255 if (T)
3256 return QualType(T, 0);
3257
Douglas Gregorc42075a2010-02-04 18:10:26 +00003258 QualType Canon = NamedType;
3259 if (!Canon.isCanonical()) {
3260 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003261 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3262 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003263 (void)CheckT;
3264 }
3265
Abramo Bagnara6150c882010-05-11 21:36:43 +00003266 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003267 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003268 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003269 return QualType(T, 0);
3270}
3271
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003272QualType
Jay Foad39c79802011-01-12 09:06:06 +00003273ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003274 llvm::FoldingSetNodeID ID;
3275 ParenType::Profile(ID, InnerType);
3276
3277 void *InsertPos = 0;
3278 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3279 if (T)
3280 return QualType(T, 0);
3281
3282 QualType Canon = InnerType;
3283 if (!Canon.isCanonical()) {
3284 Canon = getCanonicalType(InnerType);
3285 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3286 assert(!CheckT && "Paren canonical type broken");
3287 (void)CheckT;
3288 }
3289
3290 T = new (*this) ParenType(InnerType, Canon);
3291 Types.push_back(T);
3292 ParenTypes.InsertNode(T, InsertPos);
3293 return QualType(T, 0);
3294}
3295
Douglas Gregor02085352010-03-31 20:19:30 +00003296QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3297 NestedNameSpecifier *NNS,
3298 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003299 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003300 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3301
3302 if (Canon.isNull()) {
3303 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003304 ElaboratedTypeKeyword CanonKeyword = Keyword;
3305 if (Keyword == ETK_None)
3306 CanonKeyword = ETK_Typename;
3307
3308 if (CanonNNS != NNS || CanonKeyword != Keyword)
3309 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003310 }
3311
3312 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003313 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003314
3315 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003316 DependentNameType *T
3317 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003318 if (T)
3319 return QualType(T, 0);
3320
Douglas Gregor02085352010-03-31 20:19:30 +00003321 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003322 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003323 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003324 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003325}
3326
Mike Stump11289f42009-09-09 15:08:12 +00003327QualType
John McCallc392f372010-06-11 00:33:02 +00003328ASTContext::getDependentTemplateSpecializationType(
3329 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003330 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003331 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003332 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003333 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003334 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003335 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3336 ArgCopy.push_back(Args[I].getArgument());
3337 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3338 ArgCopy.size(),
3339 ArgCopy.data());
3340}
3341
3342QualType
3343ASTContext::getDependentTemplateSpecializationType(
3344 ElaboratedTypeKeyword Keyword,
3345 NestedNameSpecifier *NNS,
3346 const IdentifierInfo *Name,
3347 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003348 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003349 assert((!NNS || NNS->isDependent()) &&
3350 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003351
Douglas Gregorc42075a2010-02-04 18:10:26 +00003352 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003353 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3354 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003355
3356 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003357 DependentTemplateSpecializationType *T
3358 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003359 if (T)
3360 return QualType(T, 0);
3361
John McCallc392f372010-06-11 00:33:02 +00003362 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003363
John McCallc392f372010-06-11 00:33:02 +00003364 ElaboratedTypeKeyword CanonKeyword = Keyword;
3365 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3366
3367 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003368 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003369 for (unsigned I = 0; I != NumArgs; ++I) {
3370 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3371 if (!CanonArgs[I].structurallyEquals(Args[I]))
3372 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003373 }
3374
John McCallc392f372010-06-11 00:33:02 +00003375 QualType Canon;
3376 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3377 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3378 Name, NumArgs,
3379 CanonArgs.data());
3380
3381 // Find the insert position again.
3382 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3383 }
3384
3385 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3386 sizeof(TemplateArgument) * NumArgs),
3387 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003388 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003389 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003390 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003391 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003392 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003393}
3394
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003395QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003396 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003397 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003398 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003399
3400 assert(Pattern->containsUnexpandedParameterPack() &&
3401 "Pack expansions must expand one or more parameter packs");
3402 void *InsertPos = 0;
3403 PackExpansionType *T
3404 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3405 if (T)
3406 return QualType(T, 0);
3407
3408 QualType Canon;
3409 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003410 Canon = getCanonicalType(Pattern);
3411 // The canonical type might not contain an unexpanded parameter pack, if it
3412 // contains an alias template specialization which ignores one of its
3413 // parameters.
3414 if (Canon->containsUnexpandedParameterPack()) {
3415 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003416
Richard Smith68eea502012-07-16 00:20:35 +00003417 // Find the insert position again, in case we inserted an element into
3418 // PackExpansionTypes and invalidated our insert position.
3419 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3420 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003421 }
3422
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003423 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003424 Types.push_back(T);
3425 PackExpansionTypes.InsertNode(T, InsertPos);
3426 return QualType(T, 0);
3427}
3428
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003429/// CmpProtocolNames - Comparison predicate for sorting protocols
3430/// alphabetically.
3431static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3432 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003433 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003434}
3435
John McCall8b07ec22010-05-15 11:32:37 +00003436static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003437 unsigned NumProtocols) {
3438 if (NumProtocols == 0) return true;
3439
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003440 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3441 return false;
3442
John McCallfc93cf92009-10-22 22:37:11 +00003443 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003444 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3445 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003446 return false;
3447 return true;
3448}
3449
3450static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003451 unsigned &NumProtocols) {
3452 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003453
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003454 // Sort protocols, keyed by name.
3455 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3456
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003457 // Canonicalize.
3458 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3459 Protocols[I] = Protocols[I]->getCanonicalDecl();
3460
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003461 // Remove duplicates.
3462 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3463 NumProtocols = ProtocolsEnd-Protocols;
3464}
3465
John McCall8b07ec22010-05-15 11:32:37 +00003466QualType ASTContext::getObjCObjectType(QualType BaseType,
3467 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003468 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003469 // If the base type is an interface and there aren't any protocols
3470 // to add, then the interface type will do just fine.
3471 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3472 return BaseType;
3473
3474 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003475 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003476 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003477 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003478 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3479 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003480
John McCall8b07ec22010-05-15 11:32:37 +00003481 // Build the canonical type, which has the canonical base type and
3482 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003483 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003484 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3485 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3486 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003487 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003488 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003489 unsigned UniqueCount = NumProtocols;
3490
John McCallfc93cf92009-10-22 22:37:11 +00003491 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003492 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3493 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003494 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003495 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3496 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003497 }
3498
3499 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003500 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3501 }
3502
3503 unsigned Size = sizeof(ObjCObjectTypeImpl);
3504 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3505 void *Mem = Allocate(Size, TypeAlignment);
3506 ObjCObjectTypeImpl *T =
3507 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3508
3509 Types.push_back(T);
3510 ObjCObjectTypes.InsertNode(T, InsertPos);
3511 return QualType(T, 0);
3512}
3513
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003514/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3515/// protocol list adopt all protocols in QT's qualified-id protocol
3516/// list.
3517bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3518 ObjCInterfaceDecl *IC) {
3519 if (!QT->isObjCQualifiedIdType())
3520 return false;
3521
3522 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3523 // If both the right and left sides have qualifiers.
3524 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3525 E = OPT->qual_end(); I != E; ++I) {
3526 ObjCProtocolDecl *Proto = *I;
3527 if (!IC->ClassImplementsProtocol(Proto, false))
3528 return false;
3529 }
3530 return true;
3531 }
3532 return false;
3533}
3534
3535/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3536/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3537/// of protocols.
3538bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3539 ObjCInterfaceDecl *IDecl) {
3540 if (!QT->isObjCQualifiedIdType())
3541 return false;
3542 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3543 if (!OPT)
3544 return false;
3545 if (!IDecl->hasDefinition())
3546 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003547 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3548 CollectInheritedProtocols(IDecl, InheritedProtocols);
3549 if (InheritedProtocols.empty())
3550 return false;
3551
3552 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3553 InheritedProtocols.begin(),
3554 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003555 // If both the right and left sides have qualifiers.
3556 bool Adopts = false;
3557 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3558 E = OPT->qual_end(); I != E; ++I) {
3559 ObjCProtocolDecl *Proto = *I;
3560 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3561 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3562 break;
3563 }
3564 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003565 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003566 }
3567 return true;
3568}
3569
John McCall8b07ec22010-05-15 11:32:37 +00003570/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3571/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003572QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003573 llvm::FoldingSetNodeID ID;
3574 ObjCObjectPointerType::Profile(ID, ObjectT);
3575
3576 void *InsertPos = 0;
3577 if (ObjCObjectPointerType *QT =
3578 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3579 return QualType(QT, 0);
3580
3581 // Find the canonical object type.
3582 QualType Canonical;
3583 if (!ObjectT.isCanonical()) {
3584 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3585
3586 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003587 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3588 }
3589
Douglas Gregorf85bee62010-02-08 22:59:26 +00003590 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003591 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3592 ObjCObjectPointerType *QType =
3593 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003594
Steve Narofffb4330f2009-06-17 22:40:22 +00003595 Types.push_back(QType);
3596 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003597 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003598}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003599
Douglas Gregor1c283312010-08-11 12:19:30 +00003600/// getObjCInterfaceType - Return the unique reference to the type for the
3601/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003602QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3603 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003604 if (Decl->TypeForDecl)
3605 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003606
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003607 if (PrevDecl) {
3608 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3609 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3610 return QualType(PrevDecl->TypeForDecl, 0);
3611 }
3612
Douglas Gregor7671e532011-12-16 16:34:57 +00003613 // Prefer the definition, if there is one.
3614 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3615 Decl = Def;
3616
Douglas Gregor1c283312010-08-11 12:19:30 +00003617 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3618 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3619 Decl->TypeForDecl = T;
3620 Types.push_back(T);
3621 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003622}
3623
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003624/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3625/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003626/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003627/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003628/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003629QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003630 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003631 if (tofExpr->isTypeDependent()) {
3632 llvm::FoldingSetNodeID ID;
3633 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003634
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003635 void *InsertPos = 0;
3636 DependentTypeOfExprType *Canon
3637 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3638 if (Canon) {
3639 // We already have a "canonical" version of an identical, dependent
3640 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003641 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003642 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003643 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003644 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003645 Canon
3646 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003647 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3648 toe = Canon;
3649 }
3650 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003651 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003652 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003653 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003654 Types.push_back(toe);
3655 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003656}
3657
Steve Naroffa773cd52007-08-01 18:02:17 +00003658/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3659/// TypeOfType AST's. The only motivation to unique these nodes would be
3660/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003661/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003662/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003663QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003664 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003665 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003666 Types.push_back(tot);
3667 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003668}
3669
Anders Carlssonad6bd352009-06-24 21:24:56 +00003670
Anders Carlsson81df7b82009-06-24 19:06:50 +00003671/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3672/// DecltypeType AST's. The only motivation to unique these nodes would be
3673/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003674/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003675/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003676QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003677 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003678
3679 // C++0x [temp.type]p2:
3680 // If an expression e involves a template parameter, decltype(e) denotes a
3681 // unique dependent type. Two such decltype-specifiers refer to the same
3682 // type only if their expressions are equivalent (14.5.6.1).
3683 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003684 llvm::FoldingSetNodeID ID;
3685 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003686
Douglas Gregora21f6c32009-07-30 23:36:40 +00003687 void *InsertPos = 0;
3688 DependentDecltypeType *Canon
3689 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3690 if (Canon) {
3691 // We already have a "canonical" version of an equivalent, dependent
3692 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003693 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003694 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003695 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003696 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003697 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003698 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3699 dt = Canon;
3700 }
3701 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003702 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3703 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003704 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003705 Types.push_back(dt);
3706 return QualType(dt, 0);
3707}
3708
Alexis Hunte852b102011-05-24 22:41:36 +00003709/// getUnaryTransformationType - We don't unique these, since the memory
3710/// savings are minimal and these are rare.
3711QualType ASTContext::getUnaryTransformType(QualType BaseType,
3712 QualType UnderlyingType,
3713 UnaryTransformType::UTTKind Kind)
3714 const {
3715 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003716 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3717 Kind,
3718 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003719 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003720 Types.push_back(Ty);
3721 return QualType(Ty, 0);
3722}
3723
Richard Smith2a7d4812013-05-04 07:00:32 +00003724/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3725/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3726/// canonical deduced-but-dependent 'auto' type.
3727QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003728 bool IsDependent) const {
3729 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003730 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003731
Richard Smith2a7d4812013-05-04 07:00:32 +00003732 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003733 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003734 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003735 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003736 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3737 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003738
Richard Smith74aeef52013-04-26 16:15:35 +00003739 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003740 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003741 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003742 Types.push_back(AT);
3743 if (InsertPos)
3744 AutoTypes.InsertNode(AT, InsertPos);
3745 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003746}
3747
Eli Friedman0dfb8892011-10-06 23:00:33 +00003748/// getAtomicType - Return the uniqued reference to the atomic type for
3749/// the given value type.
3750QualType ASTContext::getAtomicType(QualType T) const {
3751 // Unique pointers, to guarantee there is only one pointer of a particular
3752 // structure.
3753 llvm::FoldingSetNodeID ID;
3754 AtomicType::Profile(ID, T);
3755
3756 void *InsertPos = 0;
3757 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3758 return QualType(AT, 0);
3759
3760 // If the atomic value type isn't canonical, this won't be a canonical type
3761 // either, so fill in the canonical type field.
3762 QualType Canonical;
3763 if (!T.isCanonical()) {
3764 Canonical = getAtomicType(getCanonicalType(T));
3765
3766 // Get the new insert position for the node we care about.
3767 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3768 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3769 }
3770 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3771 Types.push_back(New);
3772 AtomicTypes.InsertNode(New, InsertPos);
3773 return QualType(New, 0);
3774}
3775
Richard Smith02e85f32011-04-14 22:09:26 +00003776/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3777QualType ASTContext::getAutoDeductType() const {
3778 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003779 AutoDeductTy = QualType(
3780 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003781 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003782 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003783 return AutoDeductTy;
3784}
3785
3786/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3787QualType ASTContext::getAutoRRefDeductType() const {
3788 if (AutoRRefDeductTy.isNull())
3789 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3790 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3791 return AutoRRefDeductTy;
3792}
3793
Chris Lattnerfb072462007-01-23 05:45:31 +00003794/// getTagDeclType - Return the unique reference to the type for the
3795/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003796QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003797 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003798 // FIXME: What is the design on getTagDeclType when it requires casting
3799 // away const? mutable?
3800 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003801}
3802
Mike Stump11289f42009-09-09 15:08:12 +00003803/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3804/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3805/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003806CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003807 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003808}
Chris Lattnerfb072462007-01-23 05:45:31 +00003809
Hans Wennborg27541db2011-10-27 08:29:09 +00003810/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3811CanQualType ASTContext::getIntMaxType() const {
3812 return getFromTargetType(Target->getIntMaxType());
3813}
3814
3815/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3816CanQualType ASTContext::getUIntMaxType() const {
3817 return getFromTargetType(Target->getUIntMaxType());
3818}
3819
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003820/// getSignedWCharType - Return the type of "signed wchar_t".
3821/// Used when in C++, as a GCC extension.
3822QualType ASTContext::getSignedWCharType() const {
3823 // FIXME: derive from "Target" ?
3824 return WCharTy;
3825}
3826
3827/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3828/// Used when in C++, as a GCC extension.
3829QualType ASTContext::getUnsignedWCharType() const {
3830 // FIXME: derive from "Target" ?
3831 return UnsignedIntTy;
3832}
3833
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003834QualType ASTContext::getIntPtrType() const {
3835 return getFromTargetType(Target->getIntPtrType());
3836}
3837
3838QualType ASTContext::getUIntPtrType() const {
3839 return getCorrespondingUnsignedType(getIntPtrType());
3840}
3841
Hans Wennborg27541db2011-10-27 08:29:09 +00003842/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003843/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3844QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003845 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003846}
3847
Eli Friedman4e91899e2012-11-27 02:58:24 +00003848/// \brief Return the unique type for "pid_t" defined in
3849/// <sys/types.h>. We need this to compute the correct type for vfork().
3850QualType ASTContext::getProcessIDType() const {
3851 return getFromTargetType(Target->getProcessIDType());
3852}
3853
Chris Lattnera21ad802008-04-02 05:18:44 +00003854//===----------------------------------------------------------------------===//
3855// Type Operators
3856//===----------------------------------------------------------------------===//
3857
Jay Foad39c79802011-01-12 09:06:06 +00003858CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003859 // Push qualifiers into arrays, and then discard any remaining
3860 // qualifiers.
3861 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003862 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003863 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003864 QualType Result;
3865 if (isa<ArrayType>(Ty)) {
3866 Result = getArrayDecayedType(QualType(Ty,0));
3867 } else if (isa<FunctionType>(Ty)) {
3868 Result = getPointerType(QualType(Ty, 0));
3869 } else {
3870 Result = QualType(Ty, 0);
3871 }
3872
3873 return CanQualType::CreateUnsafe(Result);
3874}
3875
John McCall6c9dd522011-01-18 07:41:22 +00003876QualType ASTContext::getUnqualifiedArrayType(QualType type,
3877 Qualifiers &quals) {
3878 SplitQualType splitType = type.getSplitUnqualifiedType();
3879
3880 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3881 // the unqualified desugared type and then drops it on the floor.
3882 // We then have to strip that sugar back off with
3883 // getUnqualifiedDesugaredType(), which is silly.
3884 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003885 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003886
3887 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003888 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003889 quals = splitType.Quals;
3890 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003891 }
3892
John McCall6c9dd522011-01-18 07:41:22 +00003893 // Otherwise, recurse on the array's element type.
3894 QualType elementType = AT->getElementType();
3895 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3896
3897 // If that didn't change the element type, AT has no qualifiers, so we
3898 // can just use the results in splitType.
3899 if (elementType == unqualElementType) {
3900 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003901 quals = splitType.Quals;
3902 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003903 }
3904
3905 // Otherwise, add in the qualifiers from the outermost type, then
3906 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003907 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003908
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003909 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003910 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003911 CAT->getSizeModifier(), 0);
3912 }
3913
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003914 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003915 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003916 }
3917
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003918 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003919 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003920 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003921 VAT->getSizeModifier(),
3922 VAT->getIndexTypeCVRQualifiers(),
3923 VAT->getBracketsRange());
3924 }
3925
3926 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003927 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003928 DSAT->getSizeModifier(), 0,
3929 SourceRange());
3930}
3931
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003932/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3933/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3934/// they point to and return true. If T1 and T2 aren't pointer types
3935/// or pointer-to-member types, or if they are not similar at this
3936/// level, returns false and leaves T1 and T2 unchanged. Top-level
3937/// qualifiers on T1 and T2 are ignored. This function will typically
3938/// be called in a loop that successively "unwraps" pointer and
3939/// pointer-to-member types to compare them at each level.
3940bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3941 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3942 *T2PtrType = T2->getAs<PointerType>();
3943 if (T1PtrType && T2PtrType) {
3944 T1 = T1PtrType->getPointeeType();
3945 T2 = T2PtrType->getPointeeType();
3946 return true;
3947 }
3948
3949 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3950 *T2MPType = T2->getAs<MemberPointerType>();
3951 if (T1MPType && T2MPType &&
3952 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3953 QualType(T2MPType->getClass(), 0))) {
3954 T1 = T1MPType->getPointeeType();
3955 T2 = T2MPType->getPointeeType();
3956 return true;
3957 }
3958
David Blaikiebbafb8a2012-03-11 07:00:24 +00003959 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003960 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3961 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3962 if (T1OPType && T2OPType) {
3963 T1 = T1OPType->getPointeeType();
3964 T2 = T2OPType->getPointeeType();
3965 return true;
3966 }
3967 }
3968
3969 // FIXME: Block pointers, too?
3970
3971 return false;
3972}
3973
Jay Foad39c79802011-01-12 09:06:06 +00003974DeclarationNameInfo
3975ASTContext::getNameForTemplate(TemplateName Name,
3976 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003977 switch (Name.getKind()) {
3978 case TemplateName::QualifiedTemplate:
3979 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003980 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003981 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3982 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003983
John McCalld9dfe3a2011-06-30 08:33:18 +00003984 case TemplateName::OverloadedTemplate: {
3985 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3986 // DNInfo work in progress: CHECKME: what about DNLoc?
3987 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3988 }
3989
3990 case TemplateName::DependentTemplate: {
3991 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003992 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003993 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003994 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3995 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003996 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003997 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3998 // DNInfo work in progress: FIXME: source locations?
3999 DeclarationNameLoc DNLoc;
4000 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4001 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4002 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004003 }
4004 }
4005
John McCalld9dfe3a2011-06-30 08:33:18 +00004006 case TemplateName::SubstTemplateTemplateParm: {
4007 SubstTemplateTemplateParmStorage *subst
4008 = Name.getAsSubstTemplateTemplateParm();
4009 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4010 NameLoc);
4011 }
4012
4013 case TemplateName::SubstTemplateTemplateParmPack: {
4014 SubstTemplateTemplateParmPackStorage *subst
4015 = Name.getAsSubstTemplateTemplateParmPack();
4016 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4017 NameLoc);
4018 }
4019 }
4020
4021 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004022}
4023
Jay Foad39c79802011-01-12 09:06:06 +00004024TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004025 switch (Name.getKind()) {
4026 case TemplateName::QualifiedTemplate:
4027 case TemplateName::Template: {
4028 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004029 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004030 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004031 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4032
4033 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004034 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004035 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004036
John McCalld9dfe3a2011-06-30 08:33:18 +00004037 case TemplateName::OverloadedTemplate:
4038 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004039
John McCalld9dfe3a2011-06-30 08:33:18 +00004040 case TemplateName::DependentTemplate: {
4041 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4042 assert(DTN && "Non-dependent template names must refer to template decls.");
4043 return DTN->CanonicalTemplateName;
4044 }
4045
4046 case TemplateName::SubstTemplateTemplateParm: {
4047 SubstTemplateTemplateParmStorage *subst
4048 = Name.getAsSubstTemplateTemplateParm();
4049 return getCanonicalTemplateName(subst->getReplacement());
4050 }
4051
4052 case TemplateName::SubstTemplateTemplateParmPack: {
4053 SubstTemplateTemplateParmPackStorage *subst
4054 = Name.getAsSubstTemplateTemplateParmPack();
4055 TemplateTemplateParmDecl *canonParameter
4056 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4057 TemplateArgument canonArgPack
4058 = getCanonicalTemplateArgument(subst->getArgumentPack());
4059 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4060 }
4061 }
4062
4063 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004064}
4065
Douglas Gregoradee3e32009-11-11 23:06:43 +00004066bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4067 X = getCanonicalTemplateName(X);
4068 Y = getCanonicalTemplateName(Y);
4069 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4070}
4071
Mike Stump11289f42009-09-09 15:08:12 +00004072TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004073ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004074 switch (Arg.getKind()) {
4075 case TemplateArgument::Null:
4076 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004077
Douglas Gregora8e02e72009-07-28 23:00:59 +00004078 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004079 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004080
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004081 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004082 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4083 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004084 }
Mike Stump11289f42009-09-09 15:08:12 +00004085
Eli Friedmanb826a002012-09-26 02:36:12 +00004086 case TemplateArgument::NullPtr:
4087 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4088 /*isNullPtr*/true);
4089
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004090 case TemplateArgument::Template:
4091 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004092
4093 case TemplateArgument::TemplateExpansion:
4094 return TemplateArgument(getCanonicalTemplateName(
4095 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004096 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004097
Douglas Gregora8e02e72009-07-28 23:00:59 +00004098 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004099 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004100
Douglas Gregora8e02e72009-07-28 23:00:59 +00004101 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004102 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004103
Douglas Gregora8e02e72009-07-28 23:00:59 +00004104 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004105 if (Arg.pack_size() == 0)
4106 return Arg;
4107
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004108 TemplateArgument *CanonArgs
4109 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004110 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004111 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004112 AEnd = Arg.pack_end();
4113 A != AEnd; (void)++A, ++Idx)
4114 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004115
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004116 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004117 }
4118 }
4119
4120 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004121 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004122}
4123
Douglas Gregor333489b2009-03-27 23:10:48 +00004124NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004125ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004126 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004127 return 0;
4128
4129 switch (NNS->getKind()) {
4130 case NestedNameSpecifier::Identifier:
4131 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004132 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004133 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4134 NNS->getAsIdentifier());
4135
4136 case NestedNameSpecifier::Namespace:
4137 // A namespace is canonical; build a nested-name-specifier with
4138 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004139 return NestedNameSpecifier::Create(*this, 0,
4140 NNS->getAsNamespace()->getOriginalNamespace());
4141
4142 case NestedNameSpecifier::NamespaceAlias:
4143 // A namespace is canonical; build a nested-name-specifier with
4144 // this namespace and no prefix.
4145 return NestedNameSpecifier::Create(*this, 0,
4146 NNS->getAsNamespaceAlias()->getNamespace()
4147 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004148
4149 case NestedNameSpecifier::TypeSpec:
4150 case NestedNameSpecifier::TypeSpecWithTemplate: {
4151 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004152
4153 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4154 // break it apart into its prefix and identifier, then reconsititute those
4155 // as the canonical nested-name-specifier. This is required to canonicalize
4156 // a dependent nested-name-specifier involving typedefs of dependent-name
4157 // types, e.g.,
4158 // typedef typename T::type T1;
4159 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004160 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4161 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004162 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004163
Eli Friedman5358a0a2012-03-03 04:09:56 +00004164 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4165 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4166 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004167 return NestedNameSpecifier::Create(*this, 0, false,
4168 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004169 }
4170
4171 case NestedNameSpecifier::Global:
4172 // The global specifier is canonical and unique.
4173 return NNS;
4174 }
4175
David Blaikie8a40f702012-01-17 06:56:22 +00004176 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004177}
4178
Chris Lattner7adf0762008-08-04 07:31:14 +00004179
Jay Foad39c79802011-01-12 09:06:06 +00004180const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004181 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004182 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004183 // Handle the common positive case fast.
4184 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4185 return AT;
4186 }
Mike Stump11289f42009-09-09 15:08:12 +00004187
John McCall8ccfcb52009-09-24 19:53:00 +00004188 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004189 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004190 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004191
John McCall8ccfcb52009-09-24 19:53:00 +00004192 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004193 // implements C99 6.7.3p8: "If the specification of an array type includes
4194 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004195
Chris Lattner7adf0762008-08-04 07:31:14 +00004196 // If we get here, we either have type qualifiers on the type, or we have
4197 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004198 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004199
John McCall33ddac02011-01-19 10:06:00 +00004200 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004201 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004202
Chris Lattner7adf0762008-08-04 07:31:14 +00004203 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004204 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004205 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004206 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004207
Chris Lattner7adf0762008-08-04 07:31:14 +00004208 // Otherwise, we have an array and we have qualifiers on it. Push the
4209 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004210 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004211
Chris Lattner7adf0762008-08-04 07:31:14 +00004212 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4213 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4214 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004215 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004216 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4217 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4218 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004219 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004220
Mike Stump11289f42009-09-09 15:08:12 +00004221 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004222 = dyn_cast<DependentSizedArrayType>(ATy))
4223 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004224 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004225 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004226 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004227 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004228 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004229
Chris Lattner7adf0762008-08-04 07:31:14 +00004230 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004231 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004232 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004233 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004234 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004235 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004236}
4237
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004238QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004239 if (T->isArrayType() || T->isFunctionType())
4240 return getDecayedType(T);
4241 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004242}
4243
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004244QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004245 T = getVariableArrayDecayedType(T);
4246 T = getAdjustedParameterType(T);
4247 return T.getUnqualifiedType();
4248}
4249
Chris Lattnera21ad802008-04-02 05:18:44 +00004250/// getArrayDecayedType - Return the properly qualified result of decaying the
4251/// specified array type to a pointer. This operation is non-trivial when
4252/// handling typedefs etc. The canonical type of "T" must be an array type,
4253/// this returns a pointer to a properly qualified element of the array.
4254///
4255/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004256QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004257 // Get the element type with 'getAsArrayType' so that we don't lose any
4258 // typedefs in the element type of the array. This also handles propagation
4259 // of type qualifiers from the array type into the element type if present
4260 // (C99 6.7.3p8).
4261 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4262 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004263
Chris Lattner7adf0762008-08-04 07:31:14 +00004264 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004265
4266 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004267 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004268}
4269
John McCall33ddac02011-01-19 10:06:00 +00004270QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4271 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004272}
4273
John McCall33ddac02011-01-19 10:06:00 +00004274QualType ASTContext::getBaseElementType(QualType type) const {
4275 Qualifiers qs;
4276 while (true) {
4277 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004278 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004279 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004280
John McCall33ddac02011-01-19 10:06:00 +00004281 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004282 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004283 }
Mike Stump11289f42009-09-09 15:08:12 +00004284
John McCall33ddac02011-01-19 10:06:00 +00004285 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004286}
4287
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004288/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004289uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004290ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4291 uint64_t ElementCount = 1;
4292 do {
4293 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004294 CA = dyn_cast_or_null<ConstantArrayType>(
4295 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004296 } while (CA);
4297 return ElementCount;
4298}
4299
Steve Naroff0af91202007-04-27 21:51:21 +00004300/// getFloatingRank - Return a relative rank for floating point types.
4301/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004302static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004303 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004304 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004305
John McCall9dd450b2009-09-21 23:43:11 +00004306 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4307 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004308 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004309 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004310 case BuiltinType::Float: return FloatRank;
4311 case BuiltinType::Double: return DoubleRank;
4312 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004313 }
4314}
4315
Mike Stump11289f42009-09-09 15:08:12 +00004316/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4317/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004318/// 'typeDomain' is a real floating point or complex type.
4319/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004320QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4321 QualType Domain) const {
4322 FloatingRank EltRank = getFloatingRank(Size);
4323 if (Domain->isComplexType()) {
4324 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004325 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004326 case FloatRank: return FloatComplexTy;
4327 case DoubleRank: return DoubleComplexTy;
4328 case LongDoubleRank: return LongDoubleComplexTy;
4329 }
Steve Naroff0af91202007-04-27 21:51:21 +00004330 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004331
4332 assert(Domain->isRealFloatingType() && "Unknown domain!");
4333 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004334 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004335 case FloatRank: return FloatTy;
4336 case DoubleRank: return DoubleTy;
4337 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004338 }
David Blaikief47fa302012-01-17 02:30:50 +00004339 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004340}
4341
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004342/// getFloatingTypeOrder - Compare the rank of the two specified floating
4343/// point types, ignoring the domain of the type (i.e. 'double' ==
4344/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004345/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004346int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004347 FloatingRank LHSR = getFloatingRank(LHS);
4348 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004349
Chris Lattnerb90739d2008-04-06 23:38:49 +00004350 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004351 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004352 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004353 return 1;
4354 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004355}
4356
Chris Lattner76a00cf2008-04-06 22:59:24 +00004357/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4358/// routine will assert if passed a built-in type that isn't an integer or enum,
4359/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004360unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004361 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004362
Chris Lattner76a00cf2008-04-06 22:59:24 +00004363 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004364 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004365 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004366 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004367 case BuiltinType::Char_S:
4368 case BuiltinType::Char_U:
4369 case BuiltinType::SChar:
4370 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004371 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004372 case BuiltinType::Short:
4373 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004374 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004375 case BuiltinType::Int:
4376 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004377 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004378 case BuiltinType::Long:
4379 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004380 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004381 case BuiltinType::LongLong:
4382 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004383 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004384 case BuiltinType::Int128:
4385 case BuiltinType::UInt128:
4386 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004387 }
4388}
4389
Eli Friedman629ffb92009-08-20 04:21:42 +00004390/// \brief Whether this is a promotable bitfield reference according
4391/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4392///
4393/// \returns the type this bit-field will promote to, or NULL if no
4394/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004395QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004396 if (E->isTypeDependent() || E->isValueDependent())
4397 return QualType();
4398
John McCalld25db7e2013-05-06 21:39:12 +00004399 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004400 if (!Field)
4401 return QualType();
4402
4403 QualType FT = Field->getType();
4404
Richard Smithcaf33902011-10-10 18:28:20 +00004405 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004406 uint64_t IntSize = getTypeSize(IntTy);
4407 // GCC extension compatibility: if the bit-field size is less than or equal
4408 // to the size of int, it gets promoted no matter what its type is.
4409 // For instance, unsigned long bf : 4 gets promoted to signed int.
4410 if (BitWidth < IntSize)
4411 return IntTy;
4412
4413 if (BitWidth == IntSize)
4414 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4415
4416 // Types bigger than int are not subject to promotions, and therefore act
4417 // like the base type.
4418 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4419 // is ridiculous.
4420 return QualType();
4421}
4422
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004423/// getPromotedIntegerType - Returns the type that Promotable will
4424/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4425/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004426QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004427 assert(!Promotable.isNull());
4428 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004429 if (const EnumType *ET = Promotable->getAs<EnumType>())
4430 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004431
4432 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4433 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4434 // (3.9.1) can be converted to a prvalue of the first of the following
4435 // types that can represent all the values of its underlying type:
4436 // int, unsigned int, long int, unsigned long int, long long int, or
4437 // unsigned long long int [...]
4438 // FIXME: Is there some better way to compute this?
4439 if (BT->getKind() == BuiltinType::WChar_S ||
4440 BT->getKind() == BuiltinType::WChar_U ||
4441 BT->getKind() == BuiltinType::Char16 ||
4442 BT->getKind() == BuiltinType::Char32) {
4443 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4444 uint64_t FromSize = getTypeSize(BT);
4445 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4446 LongLongTy, UnsignedLongLongTy };
4447 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4448 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4449 if (FromSize < ToSize ||
4450 (FromSize == ToSize &&
4451 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4452 return PromoteTypes[Idx];
4453 }
4454 llvm_unreachable("char type should fit into long long");
4455 }
4456 }
4457
4458 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004459 if (Promotable->isSignedIntegerType())
4460 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004461 uint64_t PromotableSize = getIntWidth(Promotable);
4462 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004463 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4464 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4465}
4466
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004467/// \brief Recurses in pointer/array types until it finds an objc retainable
4468/// type and returns its ownership.
4469Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4470 while (!T.isNull()) {
4471 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4472 return T.getObjCLifetime();
4473 if (T->isArrayType())
4474 T = getBaseElementType(T);
4475 else if (const PointerType *PT = T->getAs<PointerType>())
4476 T = PT->getPointeeType();
4477 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004478 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004479 else
4480 break;
4481 }
4482
4483 return Qualifiers::OCL_None;
4484}
4485
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004486static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4487 // Incomplete enum types are not treated as integer types.
4488 // FIXME: In C++, enum types are never integer types.
4489 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4490 return ET->getDecl()->getIntegerType().getTypePtr();
4491 return NULL;
4492}
4493
Mike Stump11289f42009-09-09 15:08:12 +00004494/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004495/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004496/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004497int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004498 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4499 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004500
4501 // Unwrap enums to their underlying type.
4502 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4503 LHSC = getIntegerTypeForEnum(ET);
4504 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4505 RHSC = getIntegerTypeForEnum(ET);
4506
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004507 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004508
Chris Lattner76a00cf2008-04-06 22:59:24 +00004509 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4510 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004511
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004512 unsigned LHSRank = getIntegerRank(LHSC);
4513 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004514
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004515 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4516 if (LHSRank == RHSRank) return 0;
4517 return LHSRank > RHSRank ? 1 : -1;
4518 }
Mike Stump11289f42009-09-09 15:08:12 +00004519
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004520 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4521 if (LHSUnsigned) {
4522 // If the unsigned [LHS] type is larger, return it.
4523 if (LHSRank >= RHSRank)
4524 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004525
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004526 // If the signed type can represent all values of the unsigned type, it
4527 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004528 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004529 return -1;
4530 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004531
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004532 // If the unsigned [RHS] type is larger, return it.
4533 if (RHSRank >= LHSRank)
4534 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004535
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004536 // If the signed type can represent all values of the unsigned type, it
4537 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004538 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004539 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004540}
Anders Carlsson98f07902007-08-17 05:31:46 +00004541
Mike Stump11289f42009-09-09 15:08:12 +00004542// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004543QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004544 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004545 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004546 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004547
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004548 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004549
Anders Carlsson98f07902007-08-17 05:31:46 +00004550 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004551 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004552 // int flags;
4553 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004554 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004555 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004556 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004557 FieldTypes[3] = LongTy;
4558
Anders Carlsson98f07902007-08-17 05:31:46 +00004559 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004560 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004561 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004562 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004563 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004564 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004565 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004566 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004567 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004568 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004569 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004570 }
4571
Douglas Gregord5058122010-02-11 01:19:42 +00004572 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004573 }
Mike Stump11289f42009-09-09 15:08:12 +00004574
Anders Carlsson98f07902007-08-17 05:31:46 +00004575 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004576}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004577
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004578QualType ASTContext::getObjCSuperType() const {
4579 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004580 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004581 TUDecl->addDecl(ObjCSuperTypeDecl);
4582 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4583 }
4584 return ObjCSuperType;
4585}
4586
Douglas Gregor512b0772009-04-23 22:29:11 +00004587void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004588 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004589 assert(Rec && "Invalid CFConstantStringType");
4590 CFConstantStringTypeDecl = Rec->getDecl();
4591}
4592
Jay Foad39c79802011-01-12 09:06:06 +00004593QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004594 if (BlockDescriptorType)
4595 return getTagDeclType(BlockDescriptorType);
4596
Alp Toker2dea15b2013-12-17 01:22:38 +00004597 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004598 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004599 RD = buildImplicitRecord("__block_descriptor");
4600 RD->startDefinition();
4601
Mike Stumpd0153282009-10-20 02:12:22 +00004602 QualType FieldTypes[] = {
4603 UnsignedLongTy,
4604 UnsignedLongTy,
4605 };
4606
Craig Topperd6d31ac2013-07-15 08:24:27 +00004607 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004608 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004609 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004610 };
4611
4612 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004613 FieldDecl *Field = FieldDecl::Create(
4614 *this, RD, SourceLocation(), SourceLocation(),
4615 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4616 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004617 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004618 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004619 }
4620
Alp Toker2dea15b2013-12-17 01:22:38 +00004621 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004622
Alp Toker2dea15b2013-12-17 01:22:38 +00004623 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004624
4625 return getTagDeclType(BlockDescriptorType);
4626}
4627
Jay Foad39c79802011-01-12 09:06:06 +00004628QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004629 if (BlockDescriptorExtendedType)
4630 return getTagDeclType(BlockDescriptorExtendedType);
4631
Alp Toker2dea15b2013-12-17 01:22:38 +00004632 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004633 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004634 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4635 RD->startDefinition();
4636
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004637 QualType FieldTypes[] = {
4638 UnsignedLongTy,
4639 UnsignedLongTy,
4640 getPointerType(VoidPtrTy),
4641 getPointerType(VoidPtrTy)
4642 };
4643
Craig Topperd6d31ac2013-07-15 08:24:27 +00004644 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004645 "reserved",
4646 "Size",
4647 "CopyFuncPtr",
4648 "DestroyFuncPtr"
4649 };
4650
4651 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004652 FieldDecl *Field = FieldDecl::Create(
4653 *this, RD, SourceLocation(), SourceLocation(),
4654 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4655 /*BitWidth=*/0,
4656 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004657 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004658 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004659 }
4660
Alp Toker2dea15b2013-12-17 01:22:38 +00004661 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004662
Alp Toker2dea15b2013-12-17 01:22:38 +00004663 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004664 return getTagDeclType(BlockDescriptorExtendedType);
4665}
4666
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004667/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4668/// requires copy/dispose. Note that this must match the logic
4669/// in buildByrefHelpers.
4670bool ASTContext::BlockRequiresCopying(QualType Ty,
4671 const VarDecl *D) {
4672 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4673 const Expr *copyExpr = getBlockVarCopyInits(D);
4674 if (!copyExpr && record->hasTrivialDestructor()) return false;
4675
Mike Stump94967902009-10-21 18:16:27 +00004676 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004677 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004678
4679 if (!Ty->isObjCRetainableType()) return false;
4680
4681 Qualifiers qs = Ty.getQualifiers();
4682
4683 // If we have lifetime, that dominates.
4684 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4685 assert(getLangOpts().ObjCAutoRefCount);
4686
4687 switch (lifetime) {
4688 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4689
4690 // These are just bits as far as the runtime is concerned.
4691 case Qualifiers::OCL_ExplicitNone:
4692 case Qualifiers::OCL_Autoreleasing:
4693 return false;
4694
4695 // Tell the runtime that this is ARC __weak, called by the
4696 // byref routines.
4697 case Qualifiers::OCL_Weak:
4698 // ARC __strong __block variables need to be retained.
4699 case Qualifiers::OCL_Strong:
4700 return true;
4701 }
4702 llvm_unreachable("fell out of lifetime switch!");
4703 }
4704 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4705 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004706}
4707
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004708bool ASTContext::getByrefLifetime(QualType Ty,
4709 Qualifiers::ObjCLifetime &LifeTime,
4710 bool &HasByrefExtendedLayout) const {
4711
4712 if (!getLangOpts().ObjC1 ||
4713 getLangOpts().getGC() != LangOptions::NonGC)
4714 return false;
4715
4716 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004717 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004718 HasByrefExtendedLayout = true;
4719 LifeTime = Qualifiers::OCL_None;
4720 }
4721 else if (getLangOpts().ObjCAutoRefCount)
4722 LifeTime = Ty.getObjCLifetime();
4723 // MRR.
4724 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4725 LifeTime = Qualifiers::OCL_ExplicitNone;
4726 else
4727 LifeTime = Qualifiers::OCL_None;
4728 return true;
4729}
4730
Douglas Gregorbab8a962011-09-08 01:46:34 +00004731TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4732 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004733 ObjCInstanceTypeDecl =
4734 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004735 return ObjCInstanceTypeDecl;
4736}
4737
Anders Carlsson18acd442007-10-29 06:33:42 +00004738// This returns true if a type has been typedefed to BOOL:
4739// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004740static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004741 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004742 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4743 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004744
Anders Carlssond8499822007-10-29 05:01:08 +00004745 return false;
4746}
4747
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004748/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004749/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004750CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004751 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4752 return CharUnits::Zero();
4753
Ken Dyck40775002010-01-11 17:06:35 +00004754 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004755
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004756 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004757 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004758 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004759 // Treat arrays as pointers, since that's how they're passed in.
4760 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004761 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004762 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004763}
4764
4765static inline
4766std::string charUnitsToString(const CharUnits &CU) {
4767 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004768}
4769
John McCall351762c2011-02-07 10:33:21 +00004770/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004771/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004772std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4773 std::string S;
4774
David Chisnall950a9512009-11-17 19:33:30 +00004775 const BlockDecl *Decl = Expr->getBlockDecl();
4776 QualType BlockTy =
4777 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4778 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004779 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004780 getObjCEncodingForMethodParameter(
4781 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4782 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004783 else
Alp Toker314cc812014-01-25 16:55:45 +00004784 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004785 // Compute size of all parameters.
4786 // Start with computing size of a pointer in number of bytes.
4787 // FIXME: There might(should) be a better way of doing this computation!
4788 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004789 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4790 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004791 for (auto PI : Decl->params()) {
4792 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004793 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004794 if (sz.isZero())
4795 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004796 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004797 ParmOffset += sz;
4798 }
4799 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004800 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004801 // Block pointer and offset.
4802 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004803
4804 // Argument types.
4805 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00004806 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00004807 QualType PType = PVDecl->getOriginalType();
4808 if (const ArrayType *AT =
4809 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4810 // Use array's original type only if it has known number of
4811 // elements.
4812 if (!isa<ConstantArrayType>(AT))
4813 PType = PVDecl->getType();
4814 } else if (PType->isFunctionType())
4815 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004816 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004817 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4818 S, true /*Extended*/);
4819 else
4820 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004821 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004822 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004823 }
John McCall351762c2011-02-07 10:33:21 +00004824
4825 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004826}
4827
Douglas Gregora9d84932011-05-27 01:19:52 +00004828bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004829 std::string& S) {
4830 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004831 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004832 CharUnits ParmOffset;
4833 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004834 for (auto PI : Decl->params()) {
4835 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00004836 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004837 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004838 continue;
4839
David Chisnall50e4eba2010-12-30 14:05:53 +00004840 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004841 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004842 ParmOffset += sz;
4843 }
4844 S += charUnitsToString(ParmOffset);
4845 ParmOffset = CharUnits::Zero();
4846
4847 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00004848 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00004849 QualType PType = PVDecl->getOriginalType();
4850 if (const ArrayType *AT =
4851 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4852 // Use array's original type only if it has known number of
4853 // elements.
4854 if (!isa<ConstantArrayType>(AT))
4855 PType = PVDecl->getType();
4856 } else if (PType->isFunctionType())
4857 PType = PVDecl->getType();
4858 getObjCEncodingForType(PType, S);
4859 S += charUnitsToString(ParmOffset);
4860 ParmOffset += getObjCEncodingTypeSize(PType);
4861 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004862
4863 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004864}
4865
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004866/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4867/// method parameter or return type. If Extended, include class names and
4868/// block object types.
4869void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4870 QualType T, std::string& S,
4871 bool Extended) const {
4872 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4873 getObjCEncodingForTypeQualifier(QT, S);
4874 // Encode parameter type.
4875 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4876 true /*OutermostType*/,
4877 false /*EncodingProperty*/,
4878 false /*StructField*/,
4879 Extended /*EncodeBlockParameters*/,
4880 Extended /*EncodeClassNames*/);
4881}
4882
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004883/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004884/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004885bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004886 std::string& S,
4887 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004888 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004889 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004890 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4891 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004892 // Compute size of all parameters.
4893 // Start with computing size of a pointer in number of bytes.
4894 // FIXME: There might(should) be a better way of doing this computation!
4895 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004896 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004897 // The first two arguments (self and _cmd) are pointers; account for
4898 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004899 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004900 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004901 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004902 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004903 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004904 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004905 continue;
4906
Ken Dyck40775002010-01-11 17:06:35 +00004907 assert (sz.isPositive() &&
4908 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004909 ParmOffset += sz;
4910 }
Ken Dyck40775002010-01-11 17:06:35 +00004911 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004912 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004913 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004914
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004915 // Argument types.
4916 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004917 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004918 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004919 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004920 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004921 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004922 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4923 // Use array's original type only if it has known number of
4924 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004925 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004926 PType = PVDecl->getType();
4927 } else if (PType->isFunctionType())
4928 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004929 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4930 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004931 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004932 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004933 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004934
4935 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004936}
4937
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004938ObjCPropertyImplDecl *
4939ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4940 const ObjCPropertyDecl *PD,
4941 const Decl *Container) const {
4942 if (!Container)
4943 return 0;
4944 if (const ObjCCategoryImplDecl *CID =
4945 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4946 for (ObjCCategoryImplDecl::propimpl_iterator
4947 i = CID->propimpl_begin(), e = CID->propimpl_end();
4948 i != e; ++i) {
4949 ObjCPropertyImplDecl *PID = *i;
4950 if (PID->getPropertyDecl() == PD)
4951 return PID;
4952 }
4953 } else {
4954 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4955 for (ObjCCategoryImplDecl::propimpl_iterator
4956 i = OID->propimpl_begin(), e = OID->propimpl_end();
4957 i != e; ++i) {
4958 ObjCPropertyImplDecl *PID = *i;
4959 if (PID->getPropertyDecl() == PD)
4960 return PID;
4961 }
4962 }
4963 return 0;
4964}
4965
Daniel Dunbar4932b362008-08-28 04:38:10 +00004966/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004967/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004968/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4969/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004970/// Property attributes are stored as a comma-delimited C string. The simple
4971/// attributes readonly and bycopy are encoded as single characters. The
4972/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4973/// encoded as single characters, followed by an identifier. Property types
4974/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004975/// these attributes are defined by the following enumeration:
4976/// @code
4977/// enum PropertyAttributes {
4978/// kPropertyReadOnly = 'R', // property is read-only.
4979/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4980/// kPropertyByref = '&', // property is a reference to the value last assigned
4981/// kPropertyDynamic = 'D', // property is dynamic
4982/// kPropertyGetter = 'G', // followed by getter selector name
4983/// kPropertySetter = 'S', // followed by setter selector name
4984/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004985/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004986/// kPropertyWeak = 'W' // 'weak' property
4987/// kPropertyStrong = 'P' // property GC'able
4988/// kPropertyNonAtomic = 'N' // property non-atomic
4989/// };
4990/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004991void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004992 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004993 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004994 // Collect information from the property implementation decl(s).
4995 bool Dynamic = false;
4996 ObjCPropertyImplDecl *SynthesizePID = 0;
4997
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004998 if (ObjCPropertyImplDecl *PropertyImpDecl =
4999 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5000 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5001 Dynamic = true;
5002 else
5003 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005004 }
5005
5006 // FIXME: This is not very efficient.
5007 S = "T";
5008
5009 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005010 // GCC has some special rules regarding encoding of properties which
5011 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005012 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005013 true /* outermost type */,
5014 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005015
5016 if (PD->isReadOnly()) {
5017 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005018 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5019 S += ",C";
5020 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5021 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005022 } else {
5023 switch (PD->getSetterKind()) {
5024 case ObjCPropertyDecl::Assign: break;
5025 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005026 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005027 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005028 }
5029 }
5030
5031 // It really isn't clear at all what this means, since properties
5032 // are "dynamic by default".
5033 if (Dynamic)
5034 S += ",D";
5035
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005036 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5037 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005038
Daniel Dunbar4932b362008-08-28 04:38:10 +00005039 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5040 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005041 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005042 }
5043
5044 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5045 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005046 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005047 }
5048
5049 if (SynthesizePID) {
5050 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5051 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005052 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005053 }
5054
5055 // FIXME: OBJCGC: weak & strong
5056}
5057
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005058/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005059/// Another legacy compatibility encoding: 32-bit longs are encoded as
5060/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005061/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5062///
5063void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005064 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005065 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005066 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005067 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005068 else
Jay Foad39c79802011-01-12 09:06:06 +00005069 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005070 PointeeTy = IntTy;
5071 }
5072 }
5073}
5074
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005075void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005076 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005077 // We follow the behavior of gcc, expanding structures which are
5078 // directly pointed to, and expanding embedded structures. Note that
5079 // these rules are sufficient to prevent recursive encoding of the
5080 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005081 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005082 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005083}
5084
John McCall393a78d2012-12-20 02:45:14 +00005085static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5086 BuiltinType::Kind kind) {
5087 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005088 case BuiltinType::Void: return 'v';
5089 case BuiltinType::Bool: return 'B';
5090 case BuiltinType::Char_U:
5091 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005092 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005093 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005094 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005095 case BuiltinType::UInt: return 'I';
5096 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005097 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005098 case BuiltinType::UInt128: return 'T';
5099 case BuiltinType::ULongLong: return 'Q';
5100 case BuiltinType::Char_S:
5101 case BuiltinType::SChar: return 'c';
5102 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005103 case BuiltinType::WChar_S:
5104 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005105 case BuiltinType::Int: return 'i';
5106 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005107 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005108 case BuiltinType::LongLong: return 'q';
5109 case BuiltinType::Int128: return 't';
5110 case BuiltinType::Float: return 'f';
5111 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005112 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005113 case BuiltinType::NullPtr: return '*'; // like char*
5114
5115 case BuiltinType::Half:
5116 // FIXME: potentially need @encodes for these!
5117 return ' ';
5118
5119 case BuiltinType::ObjCId:
5120 case BuiltinType::ObjCClass:
5121 case BuiltinType::ObjCSel:
5122 llvm_unreachable("@encoding ObjC primitive type");
5123
5124 // OpenCL and placeholder types don't need @encodings.
5125 case BuiltinType::OCLImage1d:
5126 case BuiltinType::OCLImage1dArray:
5127 case BuiltinType::OCLImage1dBuffer:
5128 case BuiltinType::OCLImage2d:
5129 case BuiltinType::OCLImage2dArray:
5130 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005131 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005132 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005133 case BuiltinType::Dependent:
5134#define BUILTIN_TYPE(KIND, ID)
5135#define PLACEHOLDER_TYPE(KIND, ID) \
5136 case BuiltinType::KIND:
5137#include "clang/AST/BuiltinTypes.def"
5138 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005139 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005140 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005141}
5142
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005143static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5144 EnumDecl *Enum = ET->getDecl();
5145
5146 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5147 if (!Enum->isFixed())
5148 return 'i';
5149
5150 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005151 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5152 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005153}
5154
Jay Foad39c79802011-01-12 09:06:06 +00005155static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005156 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005157 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005158 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005159 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5160 // The GNU runtime requires more information; bitfields are encoded as b,
5161 // then the offset (in bits) of the first element, then the type of the
5162 // bitfield, then the size in bits. For example, in this structure:
5163 //
5164 // struct
5165 // {
5166 // int integer;
5167 // int flags:2;
5168 // };
5169 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5170 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5171 // information is not especially sensible, but we're stuck with it for
5172 // compatibility with GCC, although providing it breaks anything that
5173 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005174 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005175 const RecordDecl *RD = FD->getParent();
5176 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005177 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005178 if (const EnumType *ET = T->getAs<EnumType>())
5179 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005180 else {
5181 const BuiltinType *BT = T->castAs<BuiltinType>();
5182 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5183 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005184 }
Richard Smithcaf33902011-10-10 18:28:20 +00005185 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005186}
5187
Daniel Dunbar07d07852009-10-18 21:17:35 +00005188// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005189void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5190 bool ExpandPointedToStructures,
5191 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005192 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005193 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005194 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005195 bool StructField,
5196 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005197 bool EncodeClassNames,
5198 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005199 CanQualType CT = getCanonicalType(T);
5200 switch (CT->getTypeClass()) {
5201 case Type::Builtin:
5202 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005203 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005204 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005205 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5206 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5207 else
5208 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005209 return;
Mike Stump11289f42009-09-09 15:08:12 +00005210
John McCall393a78d2012-12-20 02:45:14 +00005211 case Type::Complex: {
5212 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005213 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005214 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005215 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005216 return;
5217 }
John McCall393a78d2012-12-20 02:45:14 +00005218
5219 case Type::Atomic: {
5220 const AtomicType *AT = T->castAs<AtomicType>();
5221 S += 'A';
5222 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5223 false, false);
5224 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005225 }
John McCall393a78d2012-12-20 02:45:14 +00005226
5227 // encoding for pointer or reference types.
5228 case Type::Pointer:
5229 case Type::LValueReference:
5230 case Type::RValueReference: {
5231 QualType PointeeTy;
5232 if (isa<PointerType>(CT)) {
5233 const PointerType *PT = T->castAs<PointerType>();
5234 if (PT->isObjCSelType()) {
5235 S += ':';
5236 return;
5237 }
5238 PointeeTy = PT->getPointeeType();
5239 } else {
5240 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5241 }
5242
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005243 bool isReadOnly = false;
5244 // For historical/compatibility reasons, the read-only qualifier of the
5245 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5246 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005247 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005248 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005249 if (OutermostType && T.isConstQualified()) {
5250 isReadOnly = true;
5251 S += 'r';
5252 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005253 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005254 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005255 while (P->getAs<PointerType>())
5256 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005257 if (P.isConstQualified()) {
5258 isReadOnly = true;
5259 S += 'r';
5260 }
5261 }
5262 if (isReadOnly) {
5263 // Another legacy compatibility encoding. Some ObjC qualifier and type
5264 // combinations need to be rearranged.
5265 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005266 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005267 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005268 }
Mike Stump11289f42009-09-09 15:08:12 +00005269
Anders Carlssond8499822007-10-29 05:01:08 +00005270 if (PointeeTy->isCharType()) {
5271 // char pointer types should be encoded as '*' unless it is a
5272 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005273 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005274 S += '*';
5275 return;
5276 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005277 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005278 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5279 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5280 S += '#';
5281 return;
5282 }
5283 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5284 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5285 S += '@';
5286 return;
5287 }
5288 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005289 }
Anders Carlssond8499822007-10-29 05:01:08 +00005290 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005291 getLegacyIntegralTypeEncoding(PointeeTy);
5292
Mike Stump11289f42009-09-09 15:08:12 +00005293 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005294 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005295 return;
5296 }
John McCall393a78d2012-12-20 02:45:14 +00005297
5298 case Type::ConstantArray:
5299 case Type::IncompleteArray:
5300 case Type::VariableArray: {
5301 const ArrayType *AT = cast<ArrayType>(CT);
5302
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005303 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005304 // Incomplete arrays are encoded as a pointer to the array element.
5305 S += '^';
5306
Mike Stump11289f42009-09-09 15:08:12 +00005307 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005308 false, ExpandStructures, FD);
5309 } else {
5310 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005311
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005312 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5313 S += llvm::utostr(CAT->getSize().getZExtValue());
5314 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005315 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005316 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5317 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005318 S += '0';
5319 }
Mike Stump11289f42009-09-09 15:08:12 +00005320
5321 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005322 false, ExpandStructures, FD);
5323 S += ']';
5324 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005325 return;
5326 }
Mike Stump11289f42009-09-09 15:08:12 +00005327
John McCall393a78d2012-12-20 02:45:14 +00005328 case Type::FunctionNoProto:
5329 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005330 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005331 return;
Mike Stump11289f42009-09-09 15:08:12 +00005332
John McCall393a78d2012-12-20 02:45:14 +00005333 case Type::Record: {
5334 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005335 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005336 // Anonymous structures print as '?'
5337 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5338 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005339 if (ClassTemplateSpecializationDecl *Spec
5340 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5341 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005342 llvm::raw_string_ostream OS(S);
5343 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005344 TemplateArgs.data(),
5345 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005346 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005347 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005348 } else {
5349 S += '?';
5350 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005351 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005352 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005353 if (!RDecl->isUnion()) {
5354 getObjCEncodingForStructureImpl(RDecl, S, FD);
5355 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005356 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005357 if (FD) {
5358 S += '"';
5359 S += Field->getNameAsString();
5360 S += '"';
5361 }
Mike Stump11289f42009-09-09 15:08:12 +00005362
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005363 // Special case bit-fields.
5364 if (Field->isBitField()) {
5365 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005366 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005367 } else {
5368 QualType qt = Field->getType();
5369 getLegacyIntegralTypeEncoding(qt);
5370 getObjCEncodingForTypeImpl(qt, S, false, true,
5371 FD, /*OutermostType*/false,
5372 /*EncodingProperty*/false,
5373 /*StructField*/true);
5374 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005375 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005376 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005377 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005378 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005379 return;
5380 }
Mike Stump11289f42009-09-09 15:08:12 +00005381
John McCall393a78d2012-12-20 02:45:14 +00005382 case Type::BlockPointer: {
5383 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005384 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005385 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005386 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005387
5388 S += '<';
5389 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005390 getObjCEncodingForTypeImpl(
5391 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5392 FD, false /* OutermostType */, EncodingProperty,
5393 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005394 // Block self
5395 S += "@?";
5396 // Block parameters
5397 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005398 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5399 E = FPT->param_type_end();
5400 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005401 getObjCEncodingForTypeImpl(*I, S,
5402 ExpandPointedToStructures,
5403 ExpandStructures,
5404 FD,
5405 false /* OutermostType */,
5406 EncodingProperty,
5407 false /* StructField */,
5408 EncodeBlockParameters,
5409 EncodeClassNames);
5410 }
5411 }
5412 S += '>';
5413 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005414 return;
5415 }
Mike Stump11289f42009-09-09 15:08:12 +00005416
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005417 case Type::ObjCObject: {
5418 // hack to match legacy encoding of *id and *Class
5419 QualType Ty = getObjCObjectPointerType(CT);
5420 if (Ty->isObjCIdType()) {
5421 S += "{objc_object=}";
5422 return;
5423 }
5424 else if (Ty->isObjCClassType()) {
5425 S += "{objc_class=}";
5426 return;
5427 }
5428 }
5429
John McCall393a78d2012-12-20 02:45:14 +00005430 case Type::ObjCInterface: {
5431 // Ignore protocol qualifiers when mangling at this level.
5432 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005433
John McCall393a78d2012-12-20 02:45:14 +00005434 // The assumption seems to be that this assert will succeed
5435 // because nested levels will have filtered out 'id' and 'Class'.
5436 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005437 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005438 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005439 S += '{';
5440 const IdentifierInfo *II = OI->getIdentifier();
5441 S += II->getName();
5442 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005443 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005444 DeepCollectObjCIvars(OI, true, Ivars);
5445 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005446 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005447 if (Field->isBitField())
5448 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005449 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005450 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5451 false, false, false, false, false,
5452 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005453 }
5454 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005455 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005456 }
Mike Stump11289f42009-09-09 15:08:12 +00005457
John McCall393a78d2012-12-20 02:45:14 +00005458 case Type::ObjCObjectPointer: {
5459 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005460 if (OPT->isObjCIdType()) {
5461 S += '@';
5462 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005463 }
Mike Stump11289f42009-09-09 15:08:12 +00005464
Steve Narofff0c86112009-10-28 22:03:49 +00005465 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5466 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5467 // Since this is a binary compatibility issue, need to consult with runtime
5468 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005469 S += '#';
5470 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005471 }
Mike Stump11289f42009-09-09 15:08:12 +00005472
Chris Lattnere7cabb92009-07-13 00:10:46 +00005473 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005474 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005475 ExpandPointedToStructures,
5476 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005477 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005478 // Note that we do extended encoding of protocol qualifer list
5479 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005480 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005481 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5482 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005483 S += '<';
5484 S += (*I)->getNameAsString();
5485 S += '>';
5486 }
5487 S += '"';
5488 }
5489 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005490 }
Mike Stump11289f42009-09-09 15:08:12 +00005491
Chris Lattnere7cabb92009-07-13 00:10:46 +00005492 QualType PointeeTy = OPT->getPointeeType();
5493 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005494 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5495 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005496 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005497 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005498 // {...};
5499 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005500 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005501 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005502 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5503 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5504 DeepCollectObjCIvars(OI, true, Ivars);
5505 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5506 if (cast<FieldDecl>(Ivars[i]) == FD) {
5507 S += '{';
5508 S += OI->getIdentifier()->getName();
5509 S += '}';
5510 return;
5511 }
5512 }
5513 }
Mike Stump11289f42009-09-09 15:08:12 +00005514 getObjCEncodingForTypeImpl(PointeeTy, S,
5515 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005516 NULL,
5517 false, false, false, false, false,
5518 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005519 return;
5520 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005521
5522 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005523 if (OPT->getInterfaceDecl() &&
5524 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005525 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005526 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005527 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5528 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005529 S += '<';
5530 S += (*I)->getNameAsString();
5531 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005532 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005533 S += '"';
5534 }
5535 return;
5536 }
Mike Stump11289f42009-09-09 15:08:12 +00005537
John McCalla9e6e8d2010-05-17 23:56:34 +00005538 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005539 // FIXME: we shoul do better than that. 'M' is available.
5540 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005541 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005542
John McCall393a78d2012-12-20 02:45:14 +00005543 case Type::Vector:
5544 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005545 // This matches gcc's encoding, even though technically it is
5546 // insufficient.
5547 // FIXME. We should do a better job than gcc.
5548 return;
John McCall393a78d2012-12-20 02:45:14 +00005549
Richard Smith27d807c2013-04-30 13:56:41 +00005550 case Type::Auto:
5551 // We could see an undeduced auto type here during error recovery.
5552 // Just ignore it.
5553 return;
5554
John McCall393a78d2012-12-20 02:45:14 +00005555#define ABSTRACT_TYPE(KIND, BASE)
5556#define TYPE(KIND, BASE)
5557#define DEPENDENT_TYPE(KIND, BASE) \
5558 case Type::KIND:
5559#define NON_CANONICAL_TYPE(KIND, BASE) \
5560 case Type::KIND:
5561#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5562 case Type::KIND:
5563#include "clang/AST/TypeNodes.def"
5564 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005565 }
John McCall393a78d2012-12-20 02:45:14 +00005566 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005567}
5568
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005569void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5570 std::string &S,
5571 const FieldDecl *FD,
5572 bool includeVBases) const {
5573 assert(RDecl && "Expected non-null RecordDecl");
5574 assert(!RDecl->isUnion() && "Should not be called for unions");
5575 if (!RDecl->getDefinition())
5576 return;
5577
5578 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5579 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5580 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5581
5582 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005583 for (const auto &BI : CXXRec->bases()) {
5584 if (!BI.isVirtual()) {
5585 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005586 if (base->isEmpty())
5587 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005588 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005589 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5590 std::make_pair(offs, base));
5591 }
5592 }
5593 }
5594
5595 unsigned i = 0;
5596 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5597 FieldEnd = RDecl->field_end();
5598 Field != FieldEnd; ++Field, ++i) {
5599 uint64_t offs = layout.getFieldOffset(i);
5600 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005601 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005602 }
5603
5604 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005605 for (const auto &BI : CXXRec->vbases()) {
5606 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005607 if (base->isEmpty())
5608 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005609 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005610 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5611 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005612 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5613 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005614 }
5615 }
5616
5617 CharUnits size;
5618 if (CXXRec) {
5619 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5620 } else {
5621 size = layout.getSize();
5622 }
5623
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005624#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005625 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005626#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005627 std::multimap<uint64_t, NamedDecl *>::iterator
5628 CurLayObj = FieldOrBaseOffsets.begin();
5629
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005630 if (CXXRec && CXXRec->isDynamicClass() &&
5631 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005632 if (FD) {
5633 S += "\"_vptr$";
5634 std::string recname = CXXRec->getNameAsString();
5635 if (recname.empty()) recname = "?";
5636 S += recname;
5637 S += '"';
5638 }
5639 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005640#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005641 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005642#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005643 }
5644
5645 if (!RDecl->hasFlexibleArrayMember()) {
5646 // Mark the end of the structure.
5647 uint64_t offs = toBits(size);
5648 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5649 std::make_pair(offs, (NamedDecl*)0));
5650 }
5651
5652 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005653#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005654 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005655 if (CurOffs < CurLayObj->first) {
5656 uint64_t padding = CurLayObj->first - CurOffs;
5657 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5658 // packing/alignment of members is different that normal, in which case
5659 // the encoding will be out-of-sync with the real layout.
5660 // If the runtime switches to just consider the size of types without
5661 // taking into account alignment, we could make padding explicit in the
5662 // encoding (e.g. using arrays of chars). The encoding strings would be
5663 // longer then though.
5664 CurOffs += padding;
5665 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005666#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005667
5668 NamedDecl *dcl = CurLayObj->second;
5669 if (dcl == 0)
5670 break; // reached end of structure.
5671
5672 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5673 // We expand the bases without their virtual bases since those are going
5674 // in the initial structure. Note that this differs from gcc which
5675 // expands virtual bases each time one is encountered in the hierarchy,
5676 // making the encoding type bigger than it really is.
5677 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005678 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005679#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005680 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005681#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005682 } else {
5683 FieldDecl *field = cast<FieldDecl>(dcl);
5684 if (FD) {
5685 S += '"';
5686 S += field->getNameAsString();
5687 S += '"';
5688 }
5689
5690 if (field->isBitField()) {
5691 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005692#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005693 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005694#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005695 } else {
5696 QualType qt = field->getType();
5697 getLegacyIntegralTypeEncoding(qt);
5698 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5699 /*OutermostType*/false,
5700 /*EncodingProperty*/false,
5701 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005702#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005703 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005704#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005705 }
5706 }
5707 }
5708}
5709
Mike Stump11289f42009-09-09 15:08:12 +00005710void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005711 std::string& S) const {
5712 if (QT & Decl::OBJC_TQ_In)
5713 S += 'n';
5714 if (QT & Decl::OBJC_TQ_Inout)
5715 S += 'N';
5716 if (QT & Decl::OBJC_TQ_Out)
5717 S += 'o';
5718 if (QT & Decl::OBJC_TQ_Bycopy)
5719 S += 'O';
5720 if (QT & Decl::OBJC_TQ_Byref)
5721 S += 'R';
5722 if (QT & Decl::OBJC_TQ_Oneway)
5723 S += 'V';
5724}
5725
Douglas Gregor3ea72692011-08-12 05:46:01 +00005726TypedefDecl *ASTContext::getObjCIdDecl() const {
5727 if (!ObjCIdDecl) {
5728 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5729 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005730 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005731 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005732 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005733}
5734
Douglas Gregor52e02802011-08-12 06:17:30 +00005735TypedefDecl *ASTContext::getObjCSelDecl() const {
5736 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005737 QualType T = getPointerType(ObjCBuiltinSelTy);
5738 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005739 }
5740 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005741}
5742
Douglas Gregor0a586182011-08-12 05:59:41 +00005743TypedefDecl *ASTContext::getObjCClassDecl() const {
5744 if (!ObjCClassDecl) {
5745 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5746 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005747 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005748 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005749 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005750}
5751
Douglas Gregord53ae832012-01-17 18:09:05 +00005752ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5753 if (!ObjCProtocolClassDecl) {
5754 ObjCProtocolClassDecl
5755 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5756 SourceLocation(),
5757 &Idents.get("Protocol"),
5758 /*PrevDecl=*/0,
5759 SourceLocation(), true);
5760 }
5761
5762 return ObjCProtocolClassDecl;
5763}
5764
Meador Inge5d3fb222012-06-16 03:34:49 +00005765//===----------------------------------------------------------------------===//
5766// __builtin_va_list Construction Functions
5767//===----------------------------------------------------------------------===//
5768
5769static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5770 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005771 QualType T = Context->getPointerType(Context->CharTy);
5772 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005773}
5774
5775static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5776 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005777 QualType T = Context->getPointerType(Context->VoidTy);
5778 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005779}
5780
Tim Northover9bb857a2013-01-31 12:13:10 +00005781static TypedefDecl *
5782CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005783 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005784 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005785 if (Context->getLangOpts().CPlusPlus) {
5786 // namespace std { struct __va_list {
5787 NamespaceDecl *NS;
5788 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5789 Context->getTranslationUnitDecl(),
5790 /*Inline*/false, SourceLocation(),
5791 SourceLocation(), &Context->Idents.get("std"),
5792 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005793 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005794 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005795 }
5796
5797 VaListTagDecl->startDefinition();
5798
5799 const size_t NumFields = 5;
5800 QualType FieldTypes[NumFields];
5801 const char *FieldNames[NumFields];
5802
5803 // void *__stack;
5804 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5805 FieldNames[0] = "__stack";
5806
5807 // void *__gr_top;
5808 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5809 FieldNames[1] = "__gr_top";
5810
5811 // void *__vr_top;
5812 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5813 FieldNames[2] = "__vr_top";
5814
5815 // int __gr_offs;
5816 FieldTypes[3] = Context->IntTy;
5817 FieldNames[3] = "__gr_offs";
5818
5819 // int __vr_offs;
5820 FieldTypes[4] = Context->IntTy;
5821 FieldNames[4] = "__vr_offs";
5822
5823 // Create fields
5824 for (unsigned i = 0; i < NumFields; ++i) {
5825 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5826 VaListTagDecl,
5827 SourceLocation(),
5828 SourceLocation(),
5829 &Context->Idents.get(FieldNames[i]),
5830 FieldTypes[i], /*TInfo=*/0,
5831 /*BitWidth=*/0,
5832 /*Mutable=*/false,
5833 ICIS_NoInit);
5834 Field->setAccess(AS_public);
5835 VaListTagDecl->addDecl(Field);
5836 }
5837 VaListTagDecl->completeDefinition();
5838 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5839 Context->VaListTagTy = VaListTagType;
5840
5841 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005842 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005843}
5844
Meador Inge5d3fb222012-06-16 03:34:49 +00005845static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5846 // typedef struct __va_list_tag {
5847 RecordDecl *VaListTagDecl;
5848
Alp Toker2dea15b2013-12-17 01:22:38 +00005849 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005850 VaListTagDecl->startDefinition();
5851
5852 const size_t NumFields = 5;
5853 QualType FieldTypes[NumFields];
5854 const char *FieldNames[NumFields];
5855
5856 // unsigned char gpr;
5857 FieldTypes[0] = Context->UnsignedCharTy;
5858 FieldNames[0] = "gpr";
5859
5860 // unsigned char fpr;
5861 FieldTypes[1] = Context->UnsignedCharTy;
5862 FieldNames[1] = "fpr";
5863
5864 // unsigned short reserved;
5865 FieldTypes[2] = Context->UnsignedShortTy;
5866 FieldNames[2] = "reserved";
5867
5868 // void* overflow_arg_area;
5869 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5870 FieldNames[3] = "overflow_arg_area";
5871
5872 // void* reg_save_area;
5873 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5874 FieldNames[4] = "reg_save_area";
5875
5876 // Create fields
5877 for (unsigned i = 0; i < NumFields; ++i) {
5878 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5879 SourceLocation(),
5880 SourceLocation(),
5881 &Context->Idents.get(FieldNames[i]),
5882 FieldTypes[i], /*TInfo=*/0,
5883 /*BitWidth=*/0,
5884 /*Mutable=*/false,
5885 ICIS_NoInit);
5886 Field->setAccess(AS_public);
5887 VaListTagDecl->addDecl(Field);
5888 }
5889 VaListTagDecl->completeDefinition();
5890 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005891 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005892
5893 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005894 TypedefDecl *VaListTagTypedefDecl =
5895 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5896
Meador Inge5d3fb222012-06-16 03:34:49 +00005897 QualType VaListTagTypedefType =
5898 Context->getTypedefType(VaListTagTypedefDecl);
5899
5900 // typedef __va_list_tag __builtin_va_list[1];
5901 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5902 QualType VaListTagArrayType
5903 = Context->getConstantArrayType(VaListTagTypedefType,
5904 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005905 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005906}
5907
5908static TypedefDecl *
5909CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5910 // typedef struct __va_list_tag {
5911 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005912 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005913 VaListTagDecl->startDefinition();
5914
5915 const size_t NumFields = 4;
5916 QualType FieldTypes[NumFields];
5917 const char *FieldNames[NumFields];
5918
5919 // unsigned gp_offset;
5920 FieldTypes[0] = Context->UnsignedIntTy;
5921 FieldNames[0] = "gp_offset";
5922
5923 // unsigned fp_offset;
5924 FieldTypes[1] = Context->UnsignedIntTy;
5925 FieldNames[1] = "fp_offset";
5926
5927 // void* overflow_arg_area;
5928 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5929 FieldNames[2] = "overflow_arg_area";
5930
5931 // void* reg_save_area;
5932 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5933 FieldNames[3] = "reg_save_area";
5934
5935 // Create fields
5936 for (unsigned i = 0; i < NumFields; ++i) {
5937 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5938 VaListTagDecl,
5939 SourceLocation(),
5940 SourceLocation(),
5941 &Context->Idents.get(FieldNames[i]),
5942 FieldTypes[i], /*TInfo=*/0,
5943 /*BitWidth=*/0,
5944 /*Mutable=*/false,
5945 ICIS_NoInit);
5946 Field->setAccess(AS_public);
5947 VaListTagDecl->addDecl(Field);
5948 }
5949 VaListTagDecl->completeDefinition();
5950 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005951 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005952
5953 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005954 TypedefDecl *VaListTagTypedefDecl =
5955 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5956
Meador Inge5d3fb222012-06-16 03:34:49 +00005957 QualType VaListTagTypedefType =
5958 Context->getTypedefType(VaListTagTypedefDecl);
5959
5960 // typedef __va_list_tag __builtin_va_list[1];
5961 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5962 QualType VaListTagArrayType
5963 = Context->getConstantArrayType(VaListTagTypedefType,
5964 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005965 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005966}
5967
5968static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5969 // typedef int __builtin_va_list[4];
5970 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5971 QualType IntArrayType
5972 = Context->getConstantArrayType(Context->IntTy,
5973 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005974 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005975}
5976
Logan Chien57086ce2012-10-10 06:56:20 +00005977static TypedefDecl *
5978CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005979 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005980 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00005981 if (Context->getLangOpts().CPlusPlus) {
5982 // namespace std { struct __va_list {
5983 NamespaceDecl *NS;
5984 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5985 Context->getTranslationUnitDecl(),
5986 /*Inline*/false, SourceLocation(),
5987 SourceLocation(), &Context->Idents.get("std"),
5988 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005989 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00005990 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00005991 }
5992
5993 VaListDecl->startDefinition();
5994
5995 // void * __ap;
5996 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5997 VaListDecl,
5998 SourceLocation(),
5999 SourceLocation(),
6000 &Context->Idents.get("__ap"),
6001 Context->getPointerType(Context->VoidTy),
6002 /*TInfo=*/0,
6003 /*BitWidth=*/0,
6004 /*Mutable=*/false,
6005 ICIS_NoInit);
6006 Field->setAccess(AS_public);
6007 VaListDecl->addDecl(Field);
6008
6009 // };
6010 VaListDecl->completeDefinition();
6011
6012 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006013 QualType T = Context->getRecordType(VaListDecl);
6014 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006015}
6016
Ulrich Weigand47445072013-05-06 16:26:41 +00006017static TypedefDecl *
6018CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6019 // typedef struct __va_list_tag {
6020 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006021 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006022 VaListTagDecl->startDefinition();
6023
6024 const size_t NumFields = 4;
6025 QualType FieldTypes[NumFields];
6026 const char *FieldNames[NumFields];
6027
6028 // long __gpr;
6029 FieldTypes[0] = Context->LongTy;
6030 FieldNames[0] = "__gpr";
6031
6032 // long __fpr;
6033 FieldTypes[1] = Context->LongTy;
6034 FieldNames[1] = "__fpr";
6035
6036 // void *__overflow_arg_area;
6037 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6038 FieldNames[2] = "__overflow_arg_area";
6039
6040 // void *__reg_save_area;
6041 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6042 FieldNames[3] = "__reg_save_area";
6043
6044 // Create fields
6045 for (unsigned i = 0; i < NumFields; ++i) {
6046 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6047 VaListTagDecl,
6048 SourceLocation(),
6049 SourceLocation(),
6050 &Context->Idents.get(FieldNames[i]),
6051 FieldTypes[i], /*TInfo=*/0,
6052 /*BitWidth=*/0,
6053 /*Mutable=*/false,
6054 ICIS_NoInit);
6055 Field->setAccess(AS_public);
6056 VaListTagDecl->addDecl(Field);
6057 }
6058 VaListTagDecl->completeDefinition();
6059 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6060 Context->VaListTagTy = VaListTagType;
6061
6062 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006063 TypedefDecl *VaListTagTypedefDecl =
6064 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006065 QualType VaListTagTypedefType =
6066 Context->getTypedefType(VaListTagTypedefDecl);
6067
6068 // typedef __va_list_tag __builtin_va_list[1];
6069 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6070 QualType VaListTagArrayType
6071 = Context->getConstantArrayType(VaListTagTypedefType,
6072 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006073
Alp Toker56b5cc92013-12-15 10:36:26 +00006074 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006075}
6076
Meador Inge5d3fb222012-06-16 03:34:49 +00006077static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6078 TargetInfo::BuiltinVaListKind Kind) {
6079 switch (Kind) {
6080 case TargetInfo::CharPtrBuiltinVaList:
6081 return CreateCharPtrBuiltinVaListDecl(Context);
6082 case TargetInfo::VoidPtrBuiltinVaList:
6083 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006084 case TargetInfo::AArch64ABIBuiltinVaList:
6085 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006086 case TargetInfo::PowerABIBuiltinVaList:
6087 return CreatePowerABIBuiltinVaListDecl(Context);
6088 case TargetInfo::X86_64ABIBuiltinVaList:
6089 return CreateX86_64ABIBuiltinVaListDecl(Context);
6090 case TargetInfo::PNaClABIBuiltinVaList:
6091 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006092 case TargetInfo::AAPCSABIBuiltinVaList:
6093 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006094 case TargetInfo::SystemZBuiltinVaList:
6095 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006096 }
6097
6098 llvm_unreachable("Unhandled __builtin_va_list type kind");
6099}
6100
6101TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006102 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006103 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006104 assert(BuiltinVaListDecl->isImplicit());
6105 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006106
6107 return BuiltinVaListDecl;
6108}
6109
Meador Ingecfb60902012-07-01 15:57:25 +00006110QualType ASTContext::getVaListTagType() const {
6111 // Force the creation of VaListTagTy by building the __builtin_va_list
6112 // declaration.
6113 if (VaListTagTy.isNull())
6114 (void) getBuiltinVaListDecl();
6115
6116 return VaListTagTy;
6117}
6118
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006119void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006120 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006121 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006122
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006123 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006124}
6125
John McCalld28ae272009-12-02 08:04:21 +00006126/// \brief Retrieve the template name that corresponds to a non-empty
6127/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006128TemplateName
6129ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6130 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006131 unsigned size = End - Begin;
6132 assert(size > 1 && "set is not overloaded!");
6133
6134 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6135 size * sizeof(FunctionTemplateDecl*));
6136 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6137
6138 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006139 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006140 NamedDecl *D = *I;
6141 assert(isa<FunctionTemplateDecl>(D) ||
6142 (isa<UsingShadowDecl>(D) &&
6143 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6144 *Storage++ = D;
6145 }
6146
6147 return TemplateName(OT);
6148}
6149
Douglas Gregordc572a32009-03-30 22:58:21 +00006150/// \brief Retrieve the template name that represents a qualified
6151/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006152TemplateName
6153ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6154 bool TemplateKeyword,
6155 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006156 assert(NNS && "Missing nested-name-specifier in qualified template name");
6157
Douglas Gregorc42075a2010-02-04 18:10:26 +00006158 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006159 llvm::FoldingSetNodeID ID;
6160 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6161
6162 void *InsertPos = 0;
6163 QualifiedTemplateName *QTN =
6164 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6165 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006166 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6167 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006168 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6169 }
6170
6171 return TemplateName(QTN);
6172}
6173
6174/// \brief Retrieve the template name that represents a dependent
6175/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006176TemplateName
6177ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6178 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006179 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006180 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006181
6182 llvm::FoldingSetNodeID ID;
6183 DependentTemplateName::Profile(ID, NNS, Name);
6184
6185 void *InsertPos = 0;
6186 DependentTemplateName *QTN =
6187 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6188
6189 if (QTN)
6190 return TemplateName(QTN);
6191
6192 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6193 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006194 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6195 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006196 } else {
6197 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006198 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6199 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006200 DependentTemplateName *CheckQTN =
6201 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6202 assert(!CheckQTN && "Dependent type name canonicalization broken");
6203 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006204 }
6205
6206 DependentTemplateNames.InsertNode(QTN, InsertPos);
6207 return TemplateName(QTN);
6208}
6209
Douglas Gregor71395fa2009-11-04 00:56:37 +00006210/// \brief Retrieve the template name that represents a dependent
6211/// template name such as \c MetaFun::template operator+.
6212TemplateName
6213ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006214 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006215 assert((!NNS || NNS->isDependent()) &&
6216 "Nested name specifier must be dependent");
6217
6218 llvm::FoldingSetNodeID ID;
6219 DependentTemplateName::Profile(ID, NNS, Operator);
6220
6221 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006222 DependentTemplateName *QTN
6223 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006224
6225 if (QTN)
6226 return TemplateName(QTN);
6227
6228 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6229 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006230 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6231 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006232 } else {
6233 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006234 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6235 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006236
6237 DependentTemplateName *CheckQTN
6238 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6239 assert(!CheckQTN && "Dependent template name canonicalization broken");
6240 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006241 }
6242
6243 DependentTemplateNames.InsertNode(QTN, InsertPos);
6244 return TemplateName(QTN);
6245}
6246
Douglas Gregor5590be02011-01-15 06:45:20 +00006247TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006248ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6249 TemplateName replacement) const {
6250 llvm::FoldingSetNodeID ID;
6251 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6252
6253 void *insertPos = 0;
6254 SubstTemplateTemplateParmStorage *subst
6255 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6256
6257 if (!subst) {
6258 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6259 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6260 }
6261
6262 return TemplateName(subst);
6263}
6264
6265TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006266ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6267 const TemplateArgument &ArgPack) const {
6268 ASTContext &Self = const_cast<ASTContext &>(*this);
6269 llvm::FoldingSetNodeID ID;
6270 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6271
6272 void *InsertPos = 0;
6273 SubstTemplateTemplateParmPackStorage *Subst
6274 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6275
6276 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006277 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006278 ArgPack.pack_size(),
6279 ArgPack.pack_begin());
6280 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6281 }
6282
6283 return TemplateName(Subst);
6284}
6285
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006286/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006287/// TargetInfo, produce the corresponding type. The unsigned @p Type
6288/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006289CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006290 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006291 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006292 case TargetInfo::SignedChar: return SignedCharTy;
6293 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006294 case TargetInfo::SignedShort: return ShortTy;
6295 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6296 case TargetInfo::SignedInt: return IntTy;
6297 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6298 case TargetInfo::SignedLong: return LongTy;
6299 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6300 case TargetInfo::SignedLongLong: return LongLongTy;
6301 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6302 }
6303
David Blaikie83d382b2011-09-23 05:06:16 +00006304 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006305}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006306
6307//===----------------------------------------------------------------------===//
6308// Type Predicates.
6309//===----------------------------------------------------------------------===//
6310
Fariborz Jahanian96207692009-02-18 21:49:28 +00006311/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6312/// garbage collection attribute.
6313///
John McCall553d45a2011-01-12 00:34:59 +00006314Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006315 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006316 return Qualifiers::GCNone;
6317
David Blaikiebbafb8a2012-03-11 07:00:24 +00006318 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006319 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6320
6321 // Default behaviour under objective-C's gc is for ObjC pointers
6322 // (or pointers to them) be treated as though they were declared
6323 // as __strong.
6324 if (GCAttrs == Qualifiers::GCNone) {
6325 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6326 return Qualifiers::Strong;
6327 else if (Ty->isPointerType())
6328 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6329 } else {
6330 // It's not valid to set GC attributes on anything that isn't a
6331 // pointer.
6332#ifndef NDEBUG
6333 QualType CT = Ty->getCanonicalTypeInternal();
6334 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6335 CT = AT->getElementType();
6336 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6337#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006338 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006339 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006340}
6341
Chris Lattner49af6a42008-04-07 06:51:04 +00006342//===----------------------------------------------------------------------===//
6343// Type Compatibility Testing
6344//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006345
Mike Stump11289f42009-09-09 15:08:12 +00006346/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006347/// compatible.
6348static bool areCompatVectorTypes(const VectorType *LHS,
6349 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006350 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006351 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006352 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006353}
6354
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006355bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6356 QualType SecondVec) {
6357 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6358 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6359
6360 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6361 return true;
6362
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006363 // Treat Neon vector types and most AltiVec vector types as if they are the
6364 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006365 const VectorType *First = FirstVec->getAs<VectorType>();
6366 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006367 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006368 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006369 First->getVectorKind() != VectorType::AltiVecPixel &&
6370 First->getVectorKind() != VectorType::AltiVecBool &&
6371 Second->getVectorKind() != VectorType::AltiVecPixel &&
6372 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006373 return true;
6374
6375 return false;
6376}
6377
Steve Naroff8e6aee52009-07-23 01:01:38 +00006378//===----------------------------------------------------------------------===//
6379// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6380//===----------------------------------------------------------------------===//
6381
6382/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6383/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006384bool
6385ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6386 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006387 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006388 return true;
6389 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6390 E = rProto->protocol_end(); PI != E; ++PI)
6391 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6392 return true;
6393 return false;
6394}
6395
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006396/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6397/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006398bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6399 QualType rhs) {
6400 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6401 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6402 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6403
6404 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6405 E = lhsQID->qual_end(); I != E; ++I) {
6406 bool match = false;
6407 ObjCProtocolDecl *lhsProto = *I;
6408 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6409 E = rhsOPT->qual_end(); J != E; ++J) {
6410 ObjCProtocolDecl *rhsProto = *J;
6411 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6412 match = true;
6413 break;
6414 }
6415 }
6416 if (!match)
6417 return false;
6418 }
6419 return true;
6420}
6421
Steve Naroff8e6aee52009-07-23 01:01:38 +00006422/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6423/// ObjCQualifiedIDType.
6424bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6425 bool compare) {
6426 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006427 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006428 lhs->isObjCIdType() || lhs->isObjCClassType())
6429 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006430 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006431 rhs->isObjCIdType() || rhs->isObjCClassType())
6432 return true;
6433
6434 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006435 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006436
Steve Naroff8e6aee52009-07-23 01:01:38 +00006437 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006438
Steve Naroff8e6aee52009-07-23 01:01:38 +00006439 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006440 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006441 // make sure we check the class hierarchy.
6442 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6443 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6444 E = lhsQID->qual_end(); I != E; ++I) {
6445 // when comparing an id<P> on lhs with a static type on rhs,
6446 // see if static class implements all of id's protocols, directly or
6447 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006448 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006449 return false;
6450 }
6451 }
6452 // If there are no qualifiers and no interface, we have an 'id'.
6453 return true;
6454 }
Mike Stump11289f42009-09-09 15:08:12 +00006455 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006456 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6457 E = lhsQID->qual_end(); I != E; ++I) {
6458 ObjCProtocolDecl *lhsProto = *I;
6459 bool match = false;
6460
6461 // when comparing an id<P> on lhs with a static type on rhs,
6462 // see if static class implements all of id's protocols, directly or
6463 // through its super class and categories.
6464 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6465 E = rhsOPT->qual_end(); J != E; ++J) {
6466 ObjCProtocolDecl *rhsProto = *J;
6467 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6468 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6469 match = true;
6470 break;
6471 }
6472 }
Mike Stump11289f42009-09-09 15:08:12 +00006473 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006474 // make sure we check the class hierarchy.
6475 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6476 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6477 E = lhsQID->qual_end(); I != E; ++I) {
6478 // when comparing an id<P> on lhs with a static type on rhs,
6479 // see if static class implements all of id's protocols, directly or
6480 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006481 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006482 match = true;
6483 break;
6484 }
6485 }
6486 }
6487 if (!match)
6488 return false;
6489 }
Mike Stump11289f42009-09-09 15:08:12 +00006490
Steve Naroff8e6aee52009-07-23 01:01:38 +00006491 return true;
6492 }
Mike Stump11289f42009-09-09 15:08:12 +00006493
Steve Naroff8e6aee52009-07-23 01:01:38 +00006494 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6495 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6496
Mike Stump11289f42009-09-09 15:08:12 +00006497 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006498 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006499 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006500 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6501 E = lhsOPT->qual_end(); I != E; ++I) {
6502 ObjCProtocolDecl *lhsProto = *I;
6503 bool match = false;
6504
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006505 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006506 // see if static class implements all of id's protocols, directly or
6507 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006508 // First, lhs protocols in the qualifier list must be found, direct
6509 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006510 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6511 E = rhsQID->qual_end(); J != E; ++J) {
6512 ObjCProtocolDecl *rhsProto = *J;
6513 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6514 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6515 match = true;
6516 break;
6517 }
6518 }
6519 if (!match)
6520 return false;
6521 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006522
6523 // Static class's protocols, or its super class or category protocols
6524 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6525 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6526 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6527 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6528 // This is rather dubious but matches gcc's behavior. If lhs has
6529 // no type qualifier and its class has no static protocol(s)
6530 // assume that it is mismatch.
6531 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6532 return false;
6533 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6534 LHSInheritedProtocols.begin(),
6535 E = LHSInheritedProtocols.end(); I != E; ++I) {
6536 bool match = false;
6537 ObjCProtocolDecl *lhsProto = (*I);
6538 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6539 E = rhsQID->qual_end(); J != E; ++J) {
6540 ObjCProtocolDecl *rhsProto = *J;
6541 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6542 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6543 match = true;
6544 break;
6545 }
6546 }
6547 if (!match)
6548 return false;
6549 }
6550 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006551 return true;
6552 }
6553 return false;
6554}
6555
Eli Friedman47f77112008-08-22 00:56:42 +00006556/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006557/// compatible for assignment from RHS to LHS. This handles validation of any
6558/// protocol qualifiers on the LHS or RHS.
6559///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006560bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6561 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006562 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6563 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6564
Steve Naroff1329fa02009-07-15 18:40:39 +00006565 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006566 if (LHS->isObjCUnqualifiedIdOrClass() ||
6567 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006568 return true;
6569
John McCall8b07ec22010-05-15 11:32:37 +00006570 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006571 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6572 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006573 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006574
6575 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6576 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6577 QualType(RHSOPT,0));
6578
John McCall8b07ec22010-05-15 11:32:37 +00006579 // If we have 2 user-defined types, fall into that path.
6580 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006581 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006582
Steve Naroff8e6aee52009-07-23 01:01:38 +00006583 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006584}
6585
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006586/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006587/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006588/// arguments in block literals. When passed as arguments, passing 'A*' where
6589/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6590/// not OK. For the return type, the opposite is not OK.
6591bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6592 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006593 const ObjCObjectPointerType *RHSOPT,
6594 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006595 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006596 return true;
6597
6598 if (LHSOPT->isObjCBuiltinType()) {
6599 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6600 }
6601
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006602 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006603 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6604 QualType(RHSOPT,0),
6605 false);
6606
6607 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6608 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6609 if (LHS && RHS) { // We have 2 user-defined types.
6610 if (LHS != RHS) {
6611 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006612 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006613 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006614 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006615 }
6616 else
6617 return true;
6618 }
6619 return false;
6620}
6621
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006622/// getIntersectionOfProtocols - This routine finds the intersection of set
6623/// of protocols inherited from two distinct objective-c pointer objects.
6624/// It is used to build composite qualifier list of the composite type of
6625/// the conditional expression involving two objective-c pointer objects.
6626static
6627void getIntersectionOfProtocols(ASTContext &Context,
6628 const ObjCObjectPointerType *LHSOPT,
6629 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006630 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006631
John McCall8b07ec22010-05-15 11:32:37 +00006632 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6633 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6634 assert(LHS->getInterface() && "LHS must have an interface base");
6635 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006636
6637 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6638 unsigned LHSNumProtocols = LHS->getNumProtocols();
6639 if (LHSNumProtocols > 0)
6640 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6641 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006642 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006643 Context.CollectInheritedProtocols(LHS->getInterface(),
6644 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006645 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6646 LHSInheritedProtocols.end());
6647 }
6648
6649 unsigned RHSNumProtocols = RHS->getNumProtocols();
6650 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006651 ObjCProtocolDecl **RHSProtocols =
6652 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006653 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6654 if (InheritedProtocolSet.count(RHSProtocols[i]))
6655 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006656 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006657 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006658 Context.CollectInheritedProtocols(RHS->getInterface(),
6659 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006660 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6661 RHSInheritedProtocols.begin(),
6662 E = RHSInheritedProtocols.end(); I != E; ++I)
6663 if (InheritedProtocolSet.count((*I)))
6664 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006665 }
6666}
6667
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006668/// areCommonBaseCompatible - Returns common base class of the two classes if
6669/// one found. Note that this is O'2 algorithm. But it will be called as the
6670/// last type comparison in a ?-exp of ObjC pointer types before a
6671/// warning is issued. So, its invokation is extremely rare.
6672QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006673 const ObjCObjectPointerType *Lptr,
6674 const ObjCObjectPointerType *Rptr) {
6675 const ObjCObjectType *LHS = Lptr->getObjectType();
6676 const ObjCObjectType *RHS = Rptr->getObjectType();
6677 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6678 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006679 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006680 return QualType();
6681
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006682 do {
John McCall8b07ec22010-05-15 11:32:37 +00006683 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006684 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006685 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006686 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6687
6688 QualType Result = QualType(LHS, 0);
6689 if (!Protocols.empty())
6690 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6691 Result = getObjCObjectPointerType(Result);
6692 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006693 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006694 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006695
6696 return QualType();
6697}
6698
John McCall8b07ec22010-05-15 11:32:37 +00006699bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6700 const ObjCObjectType *RHS) {
6701 assert(LHS->getInterface() && "LHS is not an interface type");
6702 assert(RHS->getInterface() && "RHS is not an interface type");
6703
Chris Lattner49af6a42008-04-07 06:51:04 +00006704 // Verify that the base decls are compatible: the RHS must be a subclass of
6705 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006706 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006707 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006708
Chris Lattner49af6a42008-04-07 06:51:04 +00006709 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6710 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006711 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006712 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006713
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006714 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6715 // more detailed analysis is required.
6716 if (RHS->getNumProtocols() == 0) {
6717 // OK, if LHS is a superclass of RHS *and*
6718 // this superclass is assignment compatible with LHS.
6719 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006720 bool IsSuperClass =
6721 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6722 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006723 // OK if conversion of LHS to SuperClass results in narrowing of types
6724 // ; i.e., SuperClass may implement at least one of the protocols
6725 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6726 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6727 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006728 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006729 // If super class has no protocols, it is not a match.
6730 if (SuperClassInheritedProtocols.empty())
6731 return false;
6732
6733 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6734 LHSPE = LHS->qual_end();
6735 LHSPI != LHSPE; LHSPI++) {
6736 bool SuperImplementsProtocol = false;
6737 ObjCProtocolDecl *LHSProto = (*LHSPI);
6738
6739 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6740 SuperClassInheritedProtocols.begin(),
6741 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6742 ObjCProtocolDecl *SuperClassProto = (*I);
6743 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6744 SuperImplementsProtocol = true;
6745 break;
6746 }
6747 }
6748 if (!SuperImplementsProtocol)
6749 return false;
6750 }
6751 return true;
6752 }
6753 return false;
6754 }
Mike Stump11289f42009-09-09 15:08:12 +00006755
John McCall8b07ec22010-05-15 11:32:37 +00006756 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6757 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006758 LHSPI != LHSPE; LHSPI++) {
6759 bool RHSImplementsProtocol = false;
6760
6761 // If the RHS doesn't implement the protocol on the left, the types
6762 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006763 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6764 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006765 RHSPI != RHSPE; RHSPI++) {
6766 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006767 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006768 break;
6769 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006770 }
6771 // FIXME: For better diagnostics, consider passing back the protocol name.
6772 if (!RHSImplementsProtocol)
6773 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006774 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006775 // The RHS implements all protocols listed on the LHS.
6776 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006777}
6778
Steve Naroffb7605152009-02-12 17:52:19 +00006779bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6780 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006781 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6782 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006783
Steve Naroff7cae42b2009-07-10 23:34:53 +00006784 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006785 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006786
6787 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6788 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006789}
6790
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006791bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6792 return canAssignObjCInterfaces(
6793 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6794 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6795}
6796
Mike Stump11289f42009-09-09 15:08:12 +00006797/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006798/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006799/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006800/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006801bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6802 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006803 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006804 return hasSameType(LHS, RHS);
6805
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006806 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006807}
6808
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006809bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006810 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006811}
6812
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006813bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6814 return !mergeTypes(LHS, RHS, true).isNull();
6815}
6816
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006817/// mergeTransparentUnionType - if T is a transparent union type and a member
6818/// of T is compatible with SubType, return the merged type, else return
6819/// QualType()
6820QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6821 bool OfBlockPointer,
6822 bool Unqualified) {
6823 if (const RecordType *UT = T->getAsUnionType()) {
6824 RecordDecl *UD = UT->getDecl();
6825 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006826 for (const auto *I : UD->fields()) {
6827 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006828 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6829 if (!MT.isNull())
6830 return MT;
6831 }
6832 }
6833 }
6834
6835 return QualType();
6836}
6837
Alp Toker9cacbab2014-01-20 20:26:09 +00006838/// mergeFunctionParameterTypes - merge two types which appear as function
6839/// parameter types
6840QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6841 bool OfBlockPointer,
6842 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006843 // GNU extension: two types are compatible if they appear as a function
6844 // argument, one of the types is a transparent union type and the other
6845 // type is compatible with a union member
6846 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6847 Unqualified);
6848 if (!lmerge.isNull())
6849 return lmerge;
6850
6851 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6852 Unqualified);
6853 if (!rmerge.isNull())
6854 return rmerge;
6855
6856 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6857}
6858
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006859QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006860 bool OfBlockPointer,
6861 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006862 const FunctionType *lbase = lhs->getAs<FunctionType>();
6863 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006864 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6865 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006866 bool allLTypes = true;
6867 bool allRTypes = true;
6868
6869 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006870 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006871 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006872 QualType RHS = rbase->getReturnType();
6873 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006874 bool UnqualifiedResult = Unqualified;
6875 if (!UnqualifiedResult)
6876 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006877 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006878 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006879 else
Alp Toker314cc812014-01-25 16:55:45 +00006880 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006881 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006882 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006883
6884 if (Unqualified)
6885 retType = retType.getUnqualifiedType();
6886
Alp Toker314cc812014-01-25 16:55:45 +00006887 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6888 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006889 if (Unqualified) {
6890 LRetType = LRetType.getUnqualifiedType();
6891 RRetType = RRetType.getUnqualifiedType();
6892 }
6893
6894 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006895 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006896 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006897 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006898
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006899 // FIXME: double check this
6900 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6901 // rbase->getRegParmAttr() != 0 &&
6902 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006903 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6904 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006905
Douglas Gregor8c940862010-01-18 17:14:39 +00006906 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006907 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006908 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006909
John McCall8c6b56f2010-12-15 01:06:38 +00006910 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006911 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6912 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006913 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6914 return QualType();
6915
John McCall31168b02011-06-15 23:02:42 +00006916 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6917 return QualType();
6918
John McCall8c6b56f2010-12-15 01:06:38 +00006919 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6920 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006921
Rafael Espindola8778c282012-11-29 16:09:03 +00006922 if (lbaseInfo.getNoReturn() != NoReturn)
6923 allLTypes = false;
6924 if (rbaseInfo.getNoReturn() != NoReturn)
6925 allRTypes = false;
6926
John McCall31168b02011-06-15 23:02:42 +00006927 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006928
Eli Friedman47f77112008-08-22 00:56:42 +00006929 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006930 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6931 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006932 // Compatible functions must have the same number of parameters
6933 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006934 return QualType();
6935
6936 // Variadic and non-variadic functions aren't compatible
6937 if (lproto->isVariadic() != rproto->isVariadic())
6938 return QualType();
6939
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006940 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6941 return QualType();
6942
Fariborz Jahanian97676972011-09-28 21:52:05 +00006943 if (LangOpts.ObjCAutoRefCount &&
6944 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6945 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006946
6947 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006948 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006949 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6950 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6951 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6952 QualType paramType = mergeFunctionParameterTypes(
6953 lParamType, rParamType, OfBlockPointer, Unqualified);
6954 if (paramType.isNull())
6955 return QualType();
6956
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006957 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006958 paramType = paramType.getUnqualifiedType();
6959
6960 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006961 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006962 lParamType = lParamType.getUnqualifiedType();
6963 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006964 }
Alp Toker601b22c2014-01-21 23:35:24 +00006965
6966 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006967 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00006968 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00006969 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006970 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006971
Eli Friedman47f77112008-08-22 00:56:42 +00006972 if (allLTypes) return lhs;
6973 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006974
6975 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6976 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006977 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006978 }
6979
6980 if (lproto) allRTypes = false;
6981 if (rproto) allLTypes = false;
6982
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006983 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006984 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006985 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006986 if (proto->isVariadic()) return QualType();
6987 // Check that the types are compatible with the types that
6988 // would result from default argument promotions (C99 6.7.5.3p15).
6989 // The only types actually affected are promotable integer
6990 // types and floats, which would be passed as a different
6991 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00006992 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
6993 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00006994
Eli Friedman448ce402012-08-30 00:44:15 +00006995 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006996 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00006997 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
6998 paramTy = Enum->getDecl()->getIntegerType();
6999 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007000 return QualType();
7001 }
Alp Toker601b22c2014-01-21 23:35:24 +00007002
7003 if (paramTy->isPromotableIntegerType() ||
7004 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007005 return QualType();
7006 }
7007
7008 if (allLTypes) return lhs;
7009 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007010
7011 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7012 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007013 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007014 }
7015
7016 if (allLTypes) return lhs;
7017 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007018 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007019}
7020
John McCall433c2e62013-03-21 00:10:07 +00007021/// Given that we have an enum type and a non-enum type, try to merge them.
7022static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7023 QualType other, bool isBlockReturnType) {
7024 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7025 // a signed integer type, or an unsigned integer type.
7026 // Compatibility is based on the underlying type, not the promotion
7027 // type.
7028 QualType underlyingType = ET->getDecl()->getIntegerType();
7029 if (underlyingType.isNull()) return QualType();
7030 if (Context.hasSameType(underlyingType, other))
7031 return other;
7032
7033 // In block return types, we're more permissive and accept any
7034 // integral type of the same size.
7035 if (isBlockReturnType && other->isIntegerType() &&
7036 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7037 return other;
7038
7039 return QualType();
7040}
7041
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007042QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007043 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007044 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007045 // C++ [expr]: If an expression initially has the type "reference to T", the
7046 // type is adjusted to "T" prior to any further analysis, the expression
7047 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007048 // expression is an lvalue unless the reference is an rvalue reference and
7049 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007050 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7051 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007052
7053 if (Unqualified) {
7054 LHS = LHS.getUnqualifiedType();
7055 RHS = RHS.getUnqualifiedType();
7056 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007057
Eli Friedman47f77112008-08-22 00:56:42 +00007058 QualType LHSCan = getCanonicalType(LHS),
7059 RHSCan = getCanonicalType(RHS);
7060
7061 // If two types are identical, they are compatible.
7062 if (LHSCan == RHSCan)
7063 return LHS;
7064
John McCall8ccfcb52009-09-24 19:53:00 +00007065 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007066 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7067 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007068 if (LQuals != RQuals) {
7069 // If any of these qualifiers are different, we have a type
7070 // mismatch.
7071 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007072 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7073 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007074 return QualType();
7075
7076 // Exactly one GC qualifier difference is allowed: __strong is
7077 // okay if the other type has no GC qualifier but is an Objective
7078 // C object pointer (i.e. implicitly strong by default). We fix
7079 // this by pretending that the unqualified type was actually
7080 // qualified __strong.
7081 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7082 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7083 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7084
7085 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7086 return QualType();
7087
7088 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7089 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7090 }
7091 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7092 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7093 }
Eli Friedman47f77112008-08-22 00:56:42 +00007094 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007095 }
7096
7097 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007098
Eli Friedmandcca6332009-06-01 01:22:52 +00007099 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7100 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007101
Chris Lattnerfd652912008-01-14 05:45:46 +00007102 // We want to consider the two function types to be the same for these
7103 // comparisons, just force one to the other.
7104 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7105 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007106
7107 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007108 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7109 LHSClass = Type::ConstantArray;
7110 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7111 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007112
John McCall8b07ec22010-05-15 11:32:37 +00007113 // ObjCInterfaces are just specialized ObjCObjects.
7114 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7115 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7116
Nate Begemance4d7fc2008-04-18 23:10:10 +00007117 // Canonicalize ExtVector -> Vector.
7118 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7119 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007120
Chris Lattner95554662008-04-07 05:43:21 +00007121 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007122 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007123 // Note that we only have special rules for turning block enum
7124 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007125 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007126 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007127 }
John McCall9dd450b2009-09-21 23:43:11 +00007128 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007129 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007130 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007131 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007132 if (OfBlockPointer && !BlockReturnType) {
7133 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7134 return LHS;
7135 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7136 return RHS;
7137 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007138
Eli Friedman47f77112008-08-22 00:56:42 +00007139 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007140 }
Eli Friedman47f77112008-08-22 00:56:42 +00007141
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007142 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007143 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007144#define TYPE(Class, Base)
7145#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007146#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007147#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7148#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7149#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007150 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007151
Richard Smith27d807c2013-04-30 13:56:41 +00007152 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007153 case Type::LValueReference:
7154 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007155 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007156 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007157
John McCall8b07ec22010-05-15 11:32:37 +00007158 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007159 case Type::IncompleteArray:
7160 case Type::VariableArray:
7161 case Type::FunctionProto:
7162 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007163 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007164
Chris Lattnerfd652912008-01-14 05:45:46 +00007165 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007166 {
7167 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007168 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7169 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007170 if (Unqualified) {
7171 LHSPointee = LHSPointee.getUnqualifiedType();
7172 RHSPointee = RHSPointee.getUnqualifiedType();
7173 }
7174 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7175 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007176 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007177 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007178 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007179 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007180 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007181 return getPointerType(ResultType);
7182 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007183 case Type::BlockPointer:
7184 {
7185 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007186 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7187 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007188 if (Unqualified) {
7189 LHSPointee = LHSPointee.getUnqualifiedType();
7190 RHSPointee = RHSPointee.getUnqualifiedType();
7191 }
7192 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7193 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007194 if (ResultType.isNull()) return QualType();
7195 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7196 return LHS;
7197 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7198 return RHS;
7199 return getBlockPointerType(ResultType);
7200 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007201 case Type::Atomic:
7202 {
7203 // Merge two pointer types, while trying to preserve typedef info
7204 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7205 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7206 if (Unqualified) {
7207 LHSValue = LHSValue.getUnqualifiedType();
7208 RHSValue = RHSValue.getUnqualifiedType();
7209 }
7210 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7211 Unqualified);
7212 if (ResultType.isNull()) return QualType();
7213 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7214 return LHS;
7215 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7216 return RHS;
7217 return getAtomicType(ResultType);
7218 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007219 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007220 {
7221 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7222 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7223 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7224 return QualType();
7225
7226 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7227 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007228 if (Unqualified) {
7229 LHSElem = LHSElem.getUnqualifiedType();
7230 RHSElem = RHSElem.getUnqualifiedType();
7231 }
7232
7233 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007234 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007235 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7236 return LHS;
7237 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7238 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007239 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7240 ArrayType::ArraySizeModifier(), 0);
7241 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7242 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007243 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7244 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007245 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7246 return LHS;
7247 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7248 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007249 if (LVAT) {
7250 // FIXME: This isn't correct! But tricky to implement because
7251 // the array's size has to be the size of LHS, but the type
7252 // has to be different.
7253 return LHS;
7254 }
7255 if (RVAT) {
7256 // FIXME: This isn't correct! But tricky to implement because
7257 // the array's size has to be the size of RHS, but the type
7258 // has to be different.
7259 return RHS;
7260 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007261 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7262 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007263 return getIncompleteArrayType(ResultType,
7264 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007265 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007266 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007267 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007268 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007269 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007270 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007271 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007272 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007273 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007274 case Type::Complex:
7275 // Distinct complex types are incompatible.
7276 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007277 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007278 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007279 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7280 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007281 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007282 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007283 case Type::ObjCObject: {
7284 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007285 // FIXME: This should be type compatibility, e.g. whether
7286 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007287 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7288 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7289 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007290 return LHS;
7291
Eli Friedman47f77112008-08-22 00:56:42 +00007292 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007293 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007294 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007295 if (OfBlockPointer) {
7296 if (canAssignObjCInterfacesInBlockPointer(
7297 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007298 RHS->getAs<ObjCObjectPointerType>(),
7299 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007300 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007301 return QualType();
7302 }
John McCall9dd450b2009-09-21 23:43:11 +00007303 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7304 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007305 return LHS;
7306
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007307 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007308 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007309 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007310
David Blaikie8a40f702012-01-17 06:56:22 +00007311 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007312}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007313
Fariborz Jahanian97676972011-09-28 21:52:05 +00007314bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7315 const FunctionProtoType *FromFunctionType,
7316 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007317 if (FromFunctionType->hasAnyConsumedParams() !=
7318 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007319 return false;
7320 FunctionProtoType::ExtProtoInfo FromEPI =
7321 FromFunctionType->getExtProtoInfo();
7322 FunctionProtoType::ExtProtoInfo ToEPI =
7323 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007324 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007325 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7326 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007327 return false;
7328 }
7329 return true;
7330}
7331
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007332/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7333/// 'RHS' attributes and returns the merged version; including for function
7334/// return types.
7335QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7336 QualType LHSCan = getCanonicalType(LHS),
7337 RHSCan = getCanonicalType(RHS);
7338 // If two types are identical, they are compatible.
7339 if (LHSCan == RHSCan)
7340 return LHS;
7341 if (RHSCan->isFunctionType()) {
7342 if (!LHSCan->isFunctionType())
7343 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007344 QualType OldReturnType =
7345 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007346 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007347 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007348 QualType ResReturnType =
7349 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7350 if (ResReturnType.isNull())
7351 return QualType();
7352 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7353 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7354 // In either case, use OldReturnType to build the new function type.
7355 const FunctionType *F = LHS->getAs<FunctionType>();
7356 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007357 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7358 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007359 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007360 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007361 return ResultType;
7362 }
7363 }
7364 return QualType();
7365 }
7366
7367 // If the qualifiers are different, the types can still be merged.
7368 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7369 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7370 if (LQuals != RQuals) {
7371 // If any of these qualifiers are different, we have a type mismatch.
7372 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7373 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7374 return QualType();
7375
7376 // Exactly one GC qualifier difference is allowed: __strong is
7377 // okay if the other type has no GC qualifier but is an Objective
7378 // C object pointer (i.e. implicitly strong by default). We fix
7379 // this by pretending that the unqualified type was actually
7380 // qualified __strong.
7381 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7382 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7383 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7384
7385 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7386 return QualType();
7387
7388 if (GC_L == Qualifiers::Strong)
7389 return LHS;
7390 if (GC_R == Qualifiers::Strong)
7391 return RHS;
7392 return QualType();
7393 }
7394
7395 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7396 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7397 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7398 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7399 if (ResQT == LHSBaseQT)
7400 return LHS;
7401 if (ResQT == RHSBaseQT)
7402 return RHS;
7403 }
7404 return QualType();
7405}
7406
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007407//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007408// Integer Predicates
7409//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007410
Jay Foad39c79802011-01-12 09:06:06 +00007411unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007412 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007413 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007414 if (T->isBooleanType())
7415 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007416 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007417 return (unsigned)getTypeSize(T);
7418}
7419
Abramo Bagnara13640492012-09-09 10:21:24 +00007420QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007421 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007422
7423 // Turn <4 x signed int> -> <4 x unsigned int>
7424 if (const VectorType *VTy = T->getAs<VectorType>())
7425 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007426 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007427
7428 // For enums, we return the unsigned version of the base type.
7429 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007430 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007431
7432 const BuiltinType *BTy = T->getAs<BuiltinType>();
7433 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007434 switch (BTy->getKind()) {
7435 case BuiltinType::Char_S:
7436 case BuiltinType::SChar:
7437 return UnsignedCharTy;
7438 case BuiltinType::Short:
7439 return UnsignedShortTy;
7440 case BuiltinType::Int:
7441 return UnsignedIntTy;
7442 case BuiltinType::Long:
7443 return UnsignedLongTy;
7444 case BuiltinType::LongLong:
7445 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007446 case BuiltinType::Int128:
7447 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007448 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007449 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007450 }
7451}
7452
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007453ASTMutationListener::~ASTMutationListener() { }
7454
Richard Smith1fa5d642013-05-11 05:45:24 +00007455void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7456 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007457
7458//===----------------------------------------------------------------------===//
7459// Builtin Type Computation
7460//===----------------------------------------------------------------------===//
7461
7462/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007463/// pointer over the consumed characters. This returns the resultant type. If
7464/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7465/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7466/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007467///
7468/// RequiresICE is filled in on return to indicate whether the value is required
7469/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007470static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007471 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007472 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007473 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007474 // Modifiers.
7475 int HowLong = 0;
7476 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007477 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007478
Chris Lattnerdc226c22010-10-01 22:42:38 +00007479 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007480 bool Done = false;
7481 while (!Done) {
7482 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007483 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007484 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007485 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007486 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007487 case 'S':
7488 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7489 assert(!Signed && "Can't use 'S' modifier multiple times!");
7490 Signed = true;
7491 break;
7492 case 'U':
7493 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7494 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7495 Unsigned = true;
7496 break;
7497 case 'L':
7498 assert(HowLong <= 2 && "Can't have LLLL modifier");
7499 ++HowLong;
7500 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007501 case 'W':
7502 // This modifier represents int64 type.
7503 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7504 switch (Context.getTargetInfo().getInt64Type()) {
7505 default:
7506 llvm_unreachable("Unexpected integer type");
7507 case TargetInfo::SignedLong:
7508 HowLong = 1;
7509 break;
7510 case TargetInfo::SignedLongLong:
7511 HowLong = 2;
7512 break;
7513 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007514 }
7515 }
7516
7517 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007518
Chris Lattnerecd79c62009-06-14 00:45:47 +00007519 // Read the base type.
7520 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007521 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007522 case 'v':
7523 assert(HowLong == 0 && !Signed && !Unsigned &&
7524 "Bad modifiers used with 'v'!");
7525 Type = Context.VoidTy;
7526 break;
Jack Carter24bef982013-08-15 15:16:57 +00007527 case 'h':
7528 assert(HowLong == 0 && !Signed && !Unsigned &&
7529 "Bad modifiers used with 'f'!");
7530 Type = Context.HalfTy;
7531 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007532 case 'f':
7533 assert(HowLong == 0 && !Signed && !Unsigned &&
7534 "Bad modifiers used with 'f'!");
7535 Type = Context.FloatTy;
7536 break;
7537 case 'd':
7538 assert(HowLong < 2 && !Signed && !Unsigned &&
7539 "Bad modifiers used with 'd'!");
7540 if (HowLong)
7541 Type = Context.LongDoubleTy;
7542 else
7543 Type = Context.DoubleTy;
7544 break;
7545 case 's':
7546 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7547 if (Unsigned)
7548 Type = Context.UnsignedShortTy;
7549 else
7550 Type = Context.ShortTy;
7551 break;
7552 case 'i':
7553 if (HowLong == 3)
7554 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7555 else if (HowLong == 2)
7556 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7557 else if (HowLong == 1)
7558 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7559 else
7560 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7561 break;
7562 case 'c':
7563 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7564 if (Signed)
7565 Type = Context.SignedCharTy;
7566 else if (Unsigned)
7567 Type = Context.UnsignedCharTy;
7568 else
7569 Type = Context.CharTy;
7570 break;
7571 case 'b': // boolean
7572 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7573 Type = Context.BoolTy;
7574 break;
7575 case 'z': // size_t.
7576 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7577 Type = Context.getSizeType();
7578 break;
7579 case 'F':
7580 Type = Context.getCFConstantStringType();
7581 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007582 case 'G':
7583 Type = Context.getObjCIdType();
7584 break;
7585 case 'H':
7586 Type = Context.getObjCSelType();
7587 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007588 case 'M':
7589 Type = Context.getObjCSuperType();
7590 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007591 case 'a':
7592 Type = Context.getBuiltinVaListType();
7593 assert(!Type.isNull() && "builtin va list type not initialized!");
7594 break;
7595 case 'A':
7596 // This is a "reference" to a va_list; however, what exactly
7597 // this means depends on how va_list is defined. There are two
7598 // different kinds of va_list: ones passed by value, and ones
7599 // passed by reference. An example of a by-value va_list is
7600 // x86, where va_list is a char*. An example of by-ref va_list
7601 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7602 // we want this argument to be a char*&; for x86-64, we want
7603 // it to be a __va_list_tag*.
7604 Type = Context.getBuiltinVaListType();
7605 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007606 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007607 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007608 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007609 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007610 break;
7611 case 'V': {
7612 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007613 unsigned NumElements = strtoul(Str, &End, 10);
7614 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007615 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007616
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007617 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7618 RequiresICE, false);
7619 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007620
7621 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007622 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007623 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007624 break;
7625 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007626 case 'E': {
7627 char *End;
7628
7629 unsigned NumElements = strtoul(Str, &End, 10);
7630 assert(End != Str && "Missing vector size");
7631
7632 Str = End;
7633
7634 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7635 false);
7636 Type = Context.getExtVectorType(ElementType, NumElements);
7637 break;
7638 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007639 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007640 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7641 false);
7642 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007643 Type = Context.getComplexType(ElementType);
7644 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007645 }
7646 case 'Y' : {
7647 Type = Context.getPointerDiffType();
7648 break;
7649 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007650 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007651 Type = Context.getFILEType();
7652 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007653 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007654 return QualType();
7655 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007656 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007657 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007658 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007659 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007660 else
7661 Type = Context.getjmp_bufType();
7662
Mike Stump2adb4da2009-07-28 23:47:15 +00007663 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007664 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007665 return QualType();
7666 }
7667 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007668 case 'K':
7669 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7670 Type = Context.getucontext_tType();
7671
7672 if (Type.isNull()) {
7673 Error = ASTContext::GE_Missing_ucontext;
7674 return QualType();
7675 }
7676 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007677 case 'p':
7678 Type = Context.getProcessIDType();
7679 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007680 }
Mike Stump11289f42009-09-09 15:08:12 +00007681
Chris Lattnerdc226c22010-10-01 22:42:38 +00007682 // If there are modifiers and if we're allowed to parse them, go for it.
7683 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007684 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007685 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007686 default: Done = true; --Str; break;
7687 case '*':
7688 case '&': {
7689 // Both pointers and references can have their pointee types
7690 // qualified with an address space.
7691 char *End;
7692 unsigned AddrSpace = strtoul(Str, &End, 10);
7693 if (End != Str && AddrSpace != 0) {
7694 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7695 Str = End;
7696 }
7697 if (c == '*')
7698 Type = Context.getPointerType(Type);
7699 else
7700 Type = Context.getLValueReferenceType(Type);
7701 break;
7702 }
7703 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7704 case 'C':
7705 Type = Type.withConst();
7706 break;
7707 case 'D':
7708 Type = Context.getVolatileType(Type);
7709 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007710 case 'R':
7711 Type = Type.withRestrict();
7712 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007713 }
7714 }
Chris Lattner84733392010-10-01 07:13:18 +00007715
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007716 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007717 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007718
Chris Lattnerecd79c62009-06-14 00:45:47 +00007719 return Type;
7720}
7721
7722/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007723QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007724 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007725 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007726 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007727
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007728 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007729
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007730 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007731 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007732 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7733 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007734 if (Error != GE_None)
7735 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007736
7737 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7738
Chris Lattnerecd79c62009-06-14 00:45:47 +00007739 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007740 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007741 if (Error != GE_None)
7742 return QualType();
7743
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007744 // If this argument is required to be an IntegerConstantExpression and the
7745 // caller cares, fill in the bitmask we return.
7746 if (RequiresICE && IntegerConstantArgs)
7747 *IntegerConstantArgs |= 1 << ArgTypes.size();
7748
Chris Lattnerecd79c62009-06-14 00:45:47 +00007749 // Do array -> pointer decay. The builtin should use the decayed type.
7750 if (Ty->isArrayType())
7751 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007752
Chris Lattnerecd79c62009-06-14 00:45:47 +00007753 ArgTypes.push_back(Ty);
7754 }
7755
7756 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7757 "'.' should only occur at end of builtin type list!");
7758
Reid Kleckner78af0702013-08-27 23:08:25 +00007759 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007760 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7761
7762 bool Variadic = (TypeStr[0] == '.');
7763
7764 // We really shouldn't be making a no-proto type here, especially in C++.
7765 if (ArgTypes.empty() && Variadic)
7766 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007767
John McCalldb40c7f2010-12-14 08:05:40 +00007768 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007769 EPI.ExtInfo = EI;
7770 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007771
Jordan Rose5c382722013-03-08 21:51:21 +00007772 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007773}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007774
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007775GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007776 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007777 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007778
Rafael Espindola3ae00052013-05-13 00:12:11 +00007779 GVALinkage External = GVA_StrongExternal;
7780 switch (FD->getTemplateSpecializationKind()) {
7781 case TSK_Undeclared:
7782 case TSK_ExplicitSpecialization:
7783 External = GVA_StrongExternal;
7784 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007785
Rafael Espindola3ae00052013-05-13 00:12:11 +00007786 case TSK_ExplicitInstantiationDefinition:
7787 return GVA_ExplicitTemplateInstantiation;
7788
7789 case TSK_ExplicitInstantiationDeclaration:
7790 case TSK_ImplicitInstantiation:
7791 External = GVA_TemplateInstantiation;
7792 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007793 }
7794
7795 if (!FD->isInlined())
7796 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007797
Alp Tokerbfa39342014-01-14 12:51:41 +00007798 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007799 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007800 // GNU or C99 inline semantics. Determine whether this symbol should be
7801 // externally visible.
7802 if (FD->isInlineDefinitionExternallyVisible())
7803 return External;
7804
7805 // C99 inline semantics, where the symbol is not externally visible.
7806 return GVA_C99Inline;
7807 }
7808
7809 // C++0x [temp.explicit]p9:
7810 // [ Note: The intent is that an inline function that is the subject of
7811 // an explicit instantiation declaration will still be implicitly
7812 // instantiated when used so that the body can be considered for
7813 // inlining, but that no out-of-line copy of the inline function would be
7814 // generated in the translation unit. -- end note ]
7815 if (FD->getTemplateSpecializationKind()
7816 == TSK_ExplicitInstantiationDeclaration)
7817 return GVA_C99Inline;
7818
7819 return GVA_CXXInline;
7820}
7821
7822GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007823 if (!VD->isExternallyVisible())
7824 return GVA_Internal;
7825
Richard Smith8809a0c2013-09-27 20:14:12 +00007826 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007827 case TSK_Undeclared:
7828 case TSK_ExplicitSpecialization:
7829 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007830
Rafael Espindola3ae00052013-05-13 00:12:11 +00007831 case TSK_ExplicitInstantiationDeclaration:
7832 llvm_unreachable("Variable should not be instantiated");
7833 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007834
Rafael Espindola3ae00052013-05-13 00:12:11 +00007835 case TSK_ExplicitInstantiationDefinition:
7836 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007837
Rafael Espindola3ae00052013-05-13 00:12:11 +00007838 case TSK_ImplicitInstantiation:
7839 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007840 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007841
7842 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007843}
7844
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007845bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007846 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7847 if (!VD->isFileVarDecl())
7848 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007849 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7850 // We never need to emit an uninstantiated function template.
7851 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7852 return false;
7853 } else
7854 return false;
7855
7856 // If this is a member of a class template, we do not need to emit it.
7857 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007858 return false;
7859
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007860 // Weak references don't produce any output by themselves.
7861 if (D->hasAttr<WeakRefAttr>())
7862 return false;
7863
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007864 // Aliases and used decls are required.
7865 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7866 return true;
7867
7868 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7869 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007870 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007871 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007872
7873 // Constructors and destructors are required.
7874 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7875 return true;
7876
John McCall6bd2a892013-01-25 22:31:03 +00007877 // The key function for a class is required. This rule only comes
7878 // into play when inline functions can be key functions, though.
7879 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7880 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7881 const CXXRecordDecl *RD = MD->getParent();
7882 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7883 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7884 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7885 return true;
7886 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007887 }
7888 }
7889
7890 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7891
7892 // static, static inline, always_inline, and extern inline functions can
7893 // always be deferred. Normal inline functions can be deferred in C99/C++.
7894 // Implicit template instantiations can also be deferred in C++.
7895 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007896 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007897 return false;
7898 return true;
7899 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007900
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007901 const VarDecl *VD = cast<VarDecl>(D);
7902 assert(VD->isFileVarDecl() && "Expected file scoped var");
7903
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007904 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7905 return false;
7906
Richard Smitha0e5e542012-11-12 21:38:00 +00007907 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007908 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007909 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7910 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007911
Richard Smitha0e5e542012-11-12 21:38:00 +00007912 // Variables that have destruction with side-effects are required.
7913 if (VD->getType().isDestructedType())
7914 return true;
7915
7916 // Variables that have initialization with side-effects are required.
7917 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7918 return true;
7919
7920 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007921}
Charles Davis53c59df2010-08-16 03:33:14 +00007922
Reid Kleckner78af0702013-08-27 23:08:25 +00007923CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7924 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007925 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007926 if (IsCXXMethod)
7927 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007928
Reid Kleckner78af0702013-08-27 23:08:25 +00007929 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007930}
7931
Jay Foad39c79802011-01-12 09:06:06 +00007932bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007933 // Pass through to the C++ ABI object
7934 return ABI->isNearlyEmpty(RD);
7935}
7936
Reid Kleckner96f8f932014-02-05 17:27:08 +00007937VTableContextBase *ASTContext::getVTableContext() {
7938 if (!VTContext.get()) {
7939 if (Target->getCXXABI().isMicrosoft())
7940 VTContext.reset(new MicrosoftVTableContext(*this));
7941 else
7942 VTContext.reset(new ItaniumVTableContext(*this));
7943 }
7944 return VTContext.get();
7945}
7946
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007947MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007948 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007949 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007950 case TargetCXXABI::GenericItanium:
7951 case TargetCXXABI::GenericARM:
7952 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007953 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007954 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007955 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007956 }
David Blaikie83d382b2011-09-23 05:06:16 +00007957 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007958}
7959
Charles Davis53c59df2010-08-16 03:33:14 +00007960CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007961
7962size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007963 return ASTRecordLayouts.getMemorySize() +
7964 llvm::capacity_in_bytes(ObjCLayouts) +
7965 llvm::capacity_in_bytes(KeyFunctions) +
7966 llvm::capacity_in_bytes(ObjCImpls) +
7967 llvm::capacity_in_bytes(BlockVarCopyInits) +
7968 llvm::capacity_in_bytes(DeclAttrs) +
7969 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7970 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7971 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7972 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7973 llvm::capacity_in_bytes(OverriddenMethods) +
7974 llvm::capacity_in_bytes(Types) +
7975 llvm::capacity_in_bytes(VariableArrayTypes) +
7976 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007977}
Ted Kremenek540017e2011-10-06 05:00:56 +00007978
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007979/// getIntTypeForBitwidth -
7980/// sets integer QualTy according to specified details:
7981/// bitwidth, signed/unsigned.
7982/// Returns empty type if there is no appropriate target types.
7983QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
7984 unsigned Signed) const {
7985 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
7986 CanQualType QualTy = getFromTargetType(Ty);
7987 if (!QualTy && DestWidth == 128)
7988 return Signed ? Int128Ty : UnsignedInt128Ty;
7989 return QualTy;
7990}
7991
7992/// getRealTypeForBitwidth -
7993/// sets floating point QualTy according to specified bitwidth.
7994/// Returns empty type if there is no appropriate target types.
7995QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
7996 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
7997 switch (Ty) {
7998 case TargetInfo::Float:
7999 return FloatTy;
8000 case TargetInfo::Double:
8001 return DoubleTy;
8002 case TargetInfo::LongDouble:
8003 return LongDoubleTy;
8004 case TargetInfo::NoFloat:
8005 return QualType();
8006 }
8007
8008 llvm_unreachable("Unhandled TargetInfo::RealType value");
8009}
8010
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008011void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8012 if (Number > 1)
8013 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008014}
8015
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008016unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8017 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8018 MangleNumbers.find(ND);
8019 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008020}
8021
David Majnemer2206bf52014-03-05 08:57:59 +00008022void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8023 if (Number > 1)
8024 StaticLocalNumbers[VD] = Number;
8025}
8026
8027unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8028 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8029 StaticLocalNumbers.find(VD);
8030 return I != StaticLocalNumbers.end() ? I->second : 1;
8031}
8032
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008033MangleNumberingContext &
8034ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008035 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8036 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8037 if (!MCtx)
8038 MCtx = createMangleNumberingContext();
8039 return *MCtx;
8040}
8041
8042MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8043 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008044}
8045
Ted Kremenek540017e2011-10-06 05:00:56 +00008046void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8047 ParamIndices[D] = index;
8048}
8049
8050unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8051 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8052 assert(I != ParamIndices.end() &&
8053 "ParmIndices lacks entry set by ParmVarDecl");
8054 return I->second;
8055}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008056
Richard Smithe6c01442013-06-05 00:46:14 +00008057APValue *
8058ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8059 bool MayCreate) {
8060 assert(E && E->getStorageDuration() == SD_Static &&
8061 "don't need to cache the computed value for this temporary");
8062 if (MayCreate)
8063 return &MaterializedTemporaryValues[E];
8064
8065 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8066 MaterializedTemporaryValues.find(E);
8067 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8068}
8069
Fariborz Jahanian615de762013-05-28 17:37:39 +00008070bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8071 const llvm::Triple &T = getTargetInfo().getTriple();
8072 if (!T.isOSDarwin())
8073 return false;
8074
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008075 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8076 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8077 return false;
8078
Fariborz Jahanian615de762013-05-28 17:37:39 +00008079 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8080 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8081 uint64_t Size = sizeChars.getQuantity();
8082 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8083 unsigned Align = alignChars.getQuantity();
8084 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8085 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8086}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008087
8088namespace {
8089
8090 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8091 /// parents as defined by the \c RecursiveASTVisitor.
8092 ///
8093 /// Note that the relationship described here is purely in terms of AST
8094 /// traversal - there are other relationships (for example declaration context)
8095 /// in the AST that are better modeled by special matchers.
8096 ///
8097 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8098 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8099
8100 public:
8101 /// \brief Builds and returns the translation unit's parent map.
8102 ///
8103 /// The caller takes ownership of the returned \c ParentMap.
8104 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8105 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8106 Visitor.TraverseDecl(&TU);
8107 return Visitor.Parents;
8108 }
8109
8110 private:
8111 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8112
8113 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8114 }
8115
8116 bool shouldVisitTemplateInstantiations() const {
8117 return true;
8118 }
8119 bool shouldVisitImplicitCode() const {
8120 return true;
8121 }
8122 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8123 // are not triggered during data recursion.
8124 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8125 return false;
8126 }
8127
8128 template <typename T>
8129 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8130 if (Node == NULL)
8131 return true;
8132 if (ParentStack.size() > 0)
8133 // FIXME: Currently we add the same parent multiple times, for example
8134 // when we visit all subexpressions of template instantiations; this is
8135 // suboptimal, bug benign: the only way to visit those is with
8136 // hasAncestor / hasParent, and those do not create new matches.
8137 // The plan is to enable DynTypedNode to be storable in a map or hash
8138 // map. The main problem there is to implement hash functions /
8139 // comparison operators for all types that DynTypedNode supports that
8140 // do not have pointer identity.
8141 (*Parents)[Node].push_back(ParentStack.back());
8142 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8143 bool Result = (this ->* traverse) (Node);
8144 ParentStack.pop_back();
8145 return Result;
8146 }
8147
8148 bool TraverseDecl(Decl *DeclNode) {
8149 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8150 }
8151
8152 bool TraverseStmt(Stmt *StmtNode) {
8153 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8154 }
8155
8156 ASTContext::ParentMap *Parents;
8157 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8158
8159 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8160 };
8161
8162} // end namespace
8163
8164ASTContext::ParentVector
8165ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8166 assert(Node.getMemoizationData() &&
8167 "Invariant broken: only nodes that support memoization may be "
8168 "used in the parent map.");
8169 if (!AllParents) {
8170 // We always need to run over the whole translation unit, as
8171 // hasAncestor can escape any subtree.
8172 AllParents.reset(
8173 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8174 }
8175 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8176 if (I == AllParents->end()) {
8177 return ParentVector();
8178 }
8179 return I->second;
8180}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008181
8182bool
8183ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8184 const ObjCMethodDecl *MethodImpl) {
8185 // No point trying to match an unavailable/deprecated mothod.
8186 if (MethodDecl->hasAttr<UnavailableAttr>()
8187 || MethodDecl->hasAttr<DeprecatedAttr>())
8188 return false;
8189 if (MethodDecl->getObjCDeclQualifier() !=
8190 MethodImpl->getObjCDeclQualifier())
8191 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008192 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008193 return false;
8194
8195 if (MethodDecl->param_size() != MethodImpl->param_size())
8196 return false;
8197
8198 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8199 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8200 EF = MethodDecl->param_end();
8201 IM != EM && IF != EF; ++IM, ++IF) {
8202 const ParmVarDecl *DeclVar = (*IF);
8203 const ParmVarDecl *ImplVar = (*IM);
8204 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8205 return false;
8206 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8207 return false;
8208 }
8209 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8210
8211}