blob: b98e3d4ed94ed6390be2cbfae3d7f8b68032c1a4 [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();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
330} // unnamed namespace
331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
371 } else
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000375 if (RC)
376 break;
377 }
378 }
379
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000382
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (OriginalDecl)
384 *OriginalDecl = OriginalDeclForRC;
385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
388 Raw.setRaw(RC);
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000390 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391
Aaron Ballman86c93902014-03-06 23:45:36 +0000392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
395 R = Raw;
396 }
397
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000398 return RC;
399}
400
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000401static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
406 if (!ID)
407 return;
408 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000409 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000411 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
414 }
415 }
416}
417
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000418comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000425 if (!ThisDeclInfo->TemplateParameters)
426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000427 comments::FullComment *CFC =
428 new (*this) comments::FullComment(FC->getBlocks(),
429 ThisDeclInfo);
430 return CFC;
431
432}
433
Richard Smithb39b9d52013-05-21 05:24:00 +0000434comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000436 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000437}
438
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000439comments::FullComment *ASTContext::getCommentForDecl(
440 const Decl *D,
441 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000442 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000443 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000444 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 const Decl *Canonical = D->getCanonicalDecl();
447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000449
450 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000451 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 return CFC;
455 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000456 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 }
458
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000459 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (!RC) {
463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000464 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000466 if (OMD && OMD->isPropertyAccessor())
467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000470 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000471 addRedeclaredMethods(OMD, Overridden);
472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000473 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000476 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000478 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000479 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000480 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000481 if (const TagType *TT = QT->getAs<TagType>())
482 if (const Decl *TD = TT->getDecl())
483 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000484 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000485 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487 while (IC->getSuperClass()) {
488 IC = IC->getSuperClass();
489 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496 return cloneFullComment(FC, D);
497 }
498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000500 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000501 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000502 for (const auto &I : RD->bases()) {
503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000504 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000505 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 if (Ty.isNull())
507 continue;
508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
510 continue;
511
512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000517 for (const auto &I : RD->vbases()) {
518 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000519 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000520 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000521 if (Ty.isNull())
522 continue;
523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524 if (!(VirtualBase= VirtualBase->getDefinition()))
525 continue;
526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527 return cloneFullComment(FC, D);
528 }
529 }
530 }
Craig Topper36250ad2014-05-12 05:36:57 +0000531 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000532 }
533
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000534 // If the RawComment was attached to other redeclaration of this Decl, we
535 // should parse the comment in context of that other Decl. This is important
536 // because comments can contain references to parameter names which can be
537 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000538 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000539 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000542 ParsedComments[Canonical] = FC;
543 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000544}
545
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000546void
547ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548 TemplateTemplateParmDecl *Parm) {
549 ID.AddInteger(Parm->getDepth());
550 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000551 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000552
553 TemplateParameterList *Params = Parm->getTemplateParameters();
554 ID.AddInteger(Params->size());
555 for (TemplateParameterList::const_iterator P = Params->begin(),
556 PEnd = Params->end();
557 P != PEnd; ++P) {
558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
559 ID.AddInteger(0);
560 ID.AddBoolean(TTP->isParameterPack());
561 continue;
562 }
563
564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
565 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000566 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000568 if (NTTP->isExpandedParameterPack()) {
569 ID.AddBoolean(true);
570 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572 QualType T = NTTP->getExpansionType(I);
573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
574 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000575 } else
576 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000577 continue;
578 }
579
580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
581 ID.AddInteger(2);
582 Profile(ID, TTP);
583 }
584}
585
586TemplateTemplateParmDecl *
587ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000588 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 // Check if we already have a canonical template template parameter.
590 llvm::FoldingSetNodeID ID;
591 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000592 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593 CanonicalTemplateTemplateParm *Canonical
594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
595 if (Canonical)
596 return Canonical->getParam();
597
598 // Build a canonical template parameter list.
599 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000600 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000601 CanonParams.reserve(Params->size());
602 for (TemplateParameterList::const_iterator P = Params->begin(),
603 PEnd = Params->end();
604 P != PEnd; ++P) {
605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606 CanonParams.push_back(
607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000608 SourceLocation(),
609 SourceLocation(),
610 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000611 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000612 TTP->isParameterPack()));
613 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615 QualType T = getCanonicalType(NTTP->getType());
616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617 NonTypeTemplateParmDecl *Param;
618 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 SmallVector<QualType, 2> ExpandedTypes;
620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623 ExpandedTInfos.push_back(
624 getTrivialTypeSourceInfo(ExpandedTypes.back()));
625 }
626
627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000628 SourceLocation(),
629 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000630 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000631 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 T,
633 TInfo,
634 ExpandedTypes.data(),
635 ExpandedTypes.size(),
636 ExpandedTInfos.data());
637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000657 TTP->getPosition(),
658 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000659 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateParameterList::Create(*this, SourceLocation(),
661 SourceLocation(),
662 CanonParams.data(),
663 CanonParams.size(),
664 SourceLocation()));
665
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000668 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 (void)Canonical;
670
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674 return CanonTTP;
675}
676
Charles Davis53c59df2010-08-16 03:33:14 +0000677CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000678 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000679
John McCall359b8852013-01-25 22:30:49 +0000680 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000682 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 case TargetCXXABI::iOS64:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000684 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000685 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000687 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000688 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000689 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000690 return CreateMicrosoftCXXABI(*this);
691 }
David Blaikie8a40f702012-01-17 06:56:22 +0000692 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000693}
694
Douglas Gregore8bbc122011-09-02 00:18:52 +0000695static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000696 const LangOptions &LOpts) {
697 if (LOpts.FakeAddressSpaceMap) {
698 // The fake address space map must have a distinct entry for each
699 // language-specific address space.
700 static const unsigned FakeAddrSpaceMap[] = {
701 1, // opencl_global
702 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000703 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000704 4, // opencl_generic
705 5, // cuda_device
706 6, // cuda_constant
707 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000708 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000709 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000712 }
713}
714
David Tweed31d09b02013-09-13 12:04:22 +0000715static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
716 const LangOptions &LangOpts) {
717 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000718 case LangOptions::ASMM_Target:
719 return TI.useAddressSpaceMapMangling();
720 case LangOptions::ASMM_On:
721 return true;
722 case LangOptions::ASMM_Off:
723 return false;
724 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000725 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000726}
727
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000728ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000729 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000730 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000731 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
732 DependentTemplateSpecializationTypes(this_()),
733 SubstTemplateTemplateParmPacks(this_()),
734 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
735 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000736 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
737 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
738 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000739 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
740 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
741 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
742 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000743 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
744 SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000745 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000746 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
747 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
748 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
749 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000750 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000751 TUDecl = TranslationUnitDecl::Create(*this);
752}
753
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000754ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000755 ReleaseParentMapEntries();
756
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000757 // Release the DenseMaps associated with DeclContext objects.
758 // FIXME: Is this the ideal solution?
759 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000760
Manuel Klimeka7328992013-06-03 13:51:33 +0000761 // Call all of the deallocation functions on all of their targets.
762 for (DeallocationMap::const_iterator I = Deallocations.begin(),
763 E = Deallocations.end(); I != E; ++I)
764 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
765 (I->first)((I->second)[J]);
766
Ted Kremenek076baeb2010-06-08 23:00:58 +0000767 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000768 // because they can contain DenseMaps.
769 for (llvm::DenseMap<const ObjCContainerDecl*,
770 const ASTRecordLayout*>::iterator
771 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
772 // Increment in loop to prevent using deallocated memory.
773 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
774 R->Destroy(*this);
775
Ted Kremenek076baeb2010-06-08 23:00:58 +0000776 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
777 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
780 R->Destroy(*this);
781 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000782
783 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
784 AEnd = DeclAttrs.end();
785 A != AEnd; ++A)
786 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000787
David Majnemere694f3e2015-08-14 14:43:50 +0000788 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
789 MaterializedTemporaryValues)
790 MTVPair.second->~APValue();
791
Reid Kleckner588c9372014-02-19 23:44:52 +0000792 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000793}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000794
Manuel Klimek95403e62014-05-21 13:28:59 +0000795void ASTContext::ReleaseParentMapEntries() {
796 if (!AllParents) return;
797 for (const auto &Entry : *AllParents) {
798 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
799 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
800 } else {
801 assert(Entry.second.is<ParentVector *>());
802 delete Entry.second.get<ParentVector *>();
803 }
804 }
805}
806
Douglas Gregor1a809332010-05-23 18:26:36 +0000807void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000808 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000809}
810
Mike Stump11289f42009-09-09 15:08:12 +0000811void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000812ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
813 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000814}
815
Chris Lattner4eb445d2007-01-26 01:27:23 +0000816void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000817 llvm::errs() << "\n*** AST Context Stats:\n";
818 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000819
Douglas Gregora30d0462009-05-26 14:40:08 +0000820 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000821#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000822#define ABSTRACT_TYPE(Name, Parent)
823#include "clang/AST/TypeNodes.def"
824 0 // Extra
825 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000826
Chris Lattner4eb445d2007-01-26 01:27:23 +0000827 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
828 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000829 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000830 }
831
Douglas Gregora30d0462009-05-26 14:40:08 +0000832 unsigned Idx = 0;
833 unsigned TotalBytes = 0;
834#define TYPE(Name, Parent) \
835 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000836 llvm::errs() << " " << counts[Idx] << " " << #Name \
837 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000838 TotalBytes += counts[Idx] * sizeof(Name##Type); \
839 ++Idx;
840#define ABSTRACT_TYPE(Name, Parent)
841#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000842
Chandler Carruth3c147a72011-07-04 05:32:14 +0000843 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
844
Douglas Gregor7454c562010-07-02 20:37:36 +0000845 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
847 << NumImplicitDefaultConstructors
848 << " implicit default constructors created\n";
849 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
850 << NumImplicitCopyConstructors
851 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000852 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
854 << NumImplicitMoveConstructors
855 << " implicit move constructors created\n";
856 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
857 << NumImplicitCopyAssignmentOperators
858 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000859 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000860 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
861 << NumImplicitMoveAssignmentOperators
862 << " implicit move assignment operators created\n";
863 llvm::errs() << NumImplicitDestructorsDeclared << "/"
864 << NumImplicitDestructors
865 << " implicit destructors created\n";
866
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000867 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000868 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000869 ExternalSource->PrintStats();
870 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000871
Douglas Gregor5b11d492010-07-25 17:53:33 +0000872 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000873}
874
Richard Smith42413142015-05-15 20:05:43 +0000875void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
876 bool NotifyListeners) {
877 if (NotifyListeners)
878 if (auto *Listener = getASTMutationListener())
879 Listener->RedefinedHiddenDefinition(ND, M);
880
881 if (getLangOpts().ModulesLocalVisibility)
882 MergedDefModules[ND].push_back(M);
883 else
884 ND->setHidden(false);
885}
886
887void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
888 auto It = MergedDefModules.find(ND);
889 if (It == MergedDefModules.end())
890 return;
891
892 auto &Merged = It->second;
893 llvm::DenseSet<Module*> Found;
894 for (Module *&M : Merged)
895 if (!Found.insert(M).second)
896 M = nullptr;
897 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
898}
899
Richard Smithf19e1272015-03-07 00:04:49 +0000900ExternCContextDecl *ASTContext::getExternCContextDecl() const {
901 if (!ExternCContext)
902 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
903
904 return ExternCContext;
905}
906
Alp Toker2dea15b2013-12-17 01:22:38 +0000907RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
908 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000909 SourceLocation Loc;
910 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000911 if (getLangOpts().CPlusPlus)
912 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
913 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000914 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000915 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
916 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000917 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000918 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
919 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000920 return NewDecl;
921}
922
923TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
924 StringRef Name) const {
925 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
926 TypedefDecl *NewDecl = TypedefDecl::Create(
927 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
928 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
929 NewDecl->setImplicit();
930 return NewDecl;
931}
932
Douglas Gregor801c99d2011-08-12 06:49:56 +0000933TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000934 if (!Int128Decl)
935 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000936 return Int128Decl;
937}
938
939TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000940 if (!UInt128Decl)
941 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000942 return UInt128Decl;
943}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000944
Nico Webere1687c52013-06-20 21:44:55 +0000945TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000946 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000947 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000948 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000949
Nico Webere1687c52013-06-20 21:44:55 +0000950 return Float128StubDecl;
951}
952
John McCall48f2d582009-10-23 23:03:21 +0000953void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000954 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000955 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000956 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000957}
958
Artem Belevichb5bc9232015-09-22 17:23:22 +0000959void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
960 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000961 assert((!this->Target || this->Target == &Target) &&
962 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000963 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregore8bbc122011-09-02 00:18:52 +0000965 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000966 this->AuxTarget = AuxTarget;
967
Douglas Gregore8bbc122011-09-02 00:18:52 +0000968 ABI.reset(createCXXABI(Target));
969 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000970 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000971
Chris Lattner970e54e2006-11-12 00:37:36 +0000972 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000973 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattner970e54e2006-11-12 00:37:36 +0000975 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000976 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000977 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000978 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000979 InitBuiltinType(CharTy, BuiltinType::Char_S);
980 else
981 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000982 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000983 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
984 InitBuiltinType(ShortTy, BuiltinType::Short);
985 InitBuiltinType(IntTy, BuiltinType::Int);
986 InitBuiltinType(LongTy, BuiltinType::Long);
987 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000988
Chris Lattner970e54e2006-11-12 00:37:36 +0000989 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000990 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
991 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
992 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
993 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
994 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000995
Chris Lattner970e54e2006-11-12 00:37:36 +0000996 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000997 InitBuiltinType(FloatTy, BuiltinType::Float);
998 InitBuiltinType(DoubleTy, BuiltinType::Double);
999 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001000
Chris Lattnerf122cef2009-04-30 02:43:43 +00001001 // GNU extension, 128-bit integers.
1002 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1003 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1004
Hans Wennborg0d81e012013-05-10 10:08:40 +00001005 // C++ 3.9.1p5
1006 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1007 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1008 else // -fshort-wchar makes wchar_t be unsigned.
1009 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1010 if (LangOpts.CPlusPlus && LangOpts.WChar)
1011 WideCharTy = WCharTy;
1012 else {
1013 // C99 (or C++ using -fno-wchar).
1014 WideCharTy = getFromTargetType(Target.getWCharType());
1015 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001016
James Molloy36365542012-05-04 10:55:22 +00001017 WIntTy = getFromTargetType(Target.getWIntType());
1018
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001019 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1020 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1021 else // C99
1022 Char16Ty = getFromTargetType(Target.getChar16Type());
1023
1024 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1025 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1026 else // C99
1027 Char32Ty = getFromTargetType(Target.getChar32Type());
1028
Douglas Gregor4619e432008-12-05 23:32:09 +00001029 // Placeholder type for type-dependent expressions whose type is
1030 // completely unknown. No code should ever check a type against
1031 // DependentTy and users should never see it; however, it is here to
1032 // help diagnose failures to properly check for type-dependent
1033 // expressions.
1034 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001035
John McCall36e7fe32010-10-12 00:20:44 +00001036 // Placeholder type for functions.
1037 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1038
John McCall0009fcc2011-04-26 20:42:42 +00001039 // Placeholder type for bound members.
1040 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1041
John McCall526ab472011-10-25 17:37:35 +00001042 // Placeholder type for pseudo-objects.
1043 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1044
John McCall31996342011-04-07 08:22:57 +00001045 // "any" type; useful for debugger-like clients.
1046 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1047
John McCall8a6b59a2011-10-17 18:09:15 +00001048 // Placeholder type for unbridged ARC casts.
1049 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1050
Eli Friedman34866c72012-08-31 00:14:07 +00001051 // Placeholder type for builtin functions.
1052 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1053
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001054 // Placeholder type for OMP array sections.
1055 if (LangOpts.OpenMP)
1056 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1057
Chris Lattner970e54e2006-11-12 00:37:36 +00001058 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001059 FloatComplexTy = getComplexType(FloatTy);
1060 DoubleComplexTy = getComplexType(DoubleTy);
1061 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001063 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001064 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1065 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001066 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001067
1068 if (LangOpts.OpenCL) {
1069 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1070 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1071 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1072 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1073 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001074 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1075 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1076 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1077 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1078 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1079 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1080 BuiltinType::OCLImage2dArrayMSAADepth);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001081 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001082
Guy Benyei61054192013-02-07 10:55:47 +00001083 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001084 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001085 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1086 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1087 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1088 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001089 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001090
1091 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001092 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1093 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001094
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001095 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001096
1097 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001098
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001099 // void * type
1100 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001101
1102 // nullptr type (C++0x 2.14.7)
1103 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001104
1105 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1106 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001107
1108 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001109 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001110}
1111
David Blaikie9c902b52011-09-25 23:23:43 +00001112DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001113 return SourceMgr.getDiagnostics();
1114}
1115
Douglas Gregor561eceb2010-08-30 16:49:28 +00001116AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1117 AttrVec *&Result = DeclAttrs[D];
1118 if (!Result) {
1119 void *Mem = Allocate(sizeof(AttrVec));
1120 Result = new (Mem) AttrVec;
1121 }
1122
1123 return *Result;
1124}
1125
1126/// \brief Erase the attributes corresponding to the given declaration.
1127void ASTContext::eraseDeclAttrs(const Decl *D) {
1128 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1129 if (Pos != DeclAttrs.end()) {
1130 Pos->second->~AttrVec();
1131 DeclAttrs.erase(Pos);
1132 }
1133}
1134
Larisse Voufo39a1e502013-08-06 01:03:05 +00001135// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001136MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001137ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001138 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001139 return getTemplateOrSpecializationInfo(Var)
1140 .dyn_cast<MemberSpecializationInfo *>();
1141}
1142
1143ASTContext::TemplateOrSpecializationInfo
1144ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1145 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1146 TemplateOrInstantiation.find(Var);
1147 if (Pos == TemplateOrInstantiation.end())
1148 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001149
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001150 return Pos->second;
1151}
1152
Mike Stump11289f42009-09-09 15:08:12 +00001153void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001154ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001155 TemplateSpecializationKind TSK,
1156 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001157 assert(Inst->isStaticDataMember() && "Not a static data member");
1158 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001159 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1160 Tmpl, TSK, PointOfInstantiation));
1161}
1162
1163void
1164ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1165 TemplateOrSpecializationInfo TSI) {
1166 assert(!TemplateOrInstantiation[Inst] &&
1167 "Already noted what the variable was instantiated from");
1168 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001169}
1170
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001171FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1172 const FunctionDecl *FD){
1173 assert(FD && "Specialization is 0");
1174 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001175 = ClassScopeSpecializationPattern.find(FD);
1176 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001177 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001178
1179 return Pos->second;
1180}
1181
1182void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1183 FunctionDecl *Pattern) {
1184 assert(FD && "Specialization is 0");
1185 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001186 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001187}
1188
John McCalle61f2ba2009-11-18 02:36:19 +00001189NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001190ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001191 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001192 = InstantiatedFromUsingDecl.find(UUD);
1193 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001194 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001195
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001196 return Pos->second;
1197}
1198
1199void
John McCallb96ec562009-12-04 22:46:56 +00001200ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1201 assert((isa<UsingDecl>(Pattern) ||
1202 isa<UnresolvedUsingValueDecl>(Pattern) ||
1203 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1204 "pattern decl is not a using decl");
1205 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1206 InstantiatedFromUsingDecl[Inst] = Pattern;
1207}
1208
1209UsingShadowDecl *
1210ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1211 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1212 = InstantiatedFromUsingShadowDecl.find(Inst);
1213 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001214 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001215
1216 return Pos->second;
1217}
1218
1219void
1220ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1221 UsingShadowDecl *Pattern) {
1222 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1223 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001224}
1225
Anders Carlsson5da84842009-09-01 04:26:58 +00001226FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1227 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1228 = InstantiatedFromUnnamedFieldDecl.find(Field);
1229 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001230 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001231
Anders Carlsson5da84842009-09-01 04:26:58 +00001232 return Pos->second;
1233}
1234
1235void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1236 FieldDecl *Tmpl) {
1237 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1238 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1239 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1240 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001241
Anders Carlsson5da84842009-09-01 04:26:58 +00001242 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1243}
1244
Douglas Gregor832940b2010-03-02 23:58:15 +00001245ASTContext::overridden_cxx_method_iterator
1246ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1247 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001248 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001249 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001250 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001251
1252 return Pos->second.begin();
1253}
1254
1255ASTContext::overridden_cxx_method_iterator
1256ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1257 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001258 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001259 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001260 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001261
1262 return Pos->second.end();
1263}
1264
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001265unsigned
1266ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1267 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001268 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001269 if (Pos == OverriddenMethods.end())
1270 return 0;
1271
1272 return Pos->second.size();
1273}
1274
Douglas Gregor832940b2010-03-02 23:58:15 +00001275void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1276 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001277 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001278 OverriddenMethods[Method].push_back(Overridden);
1279}
1280
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001281void ASTContext::getOverriddenMethods(
1282 const NamedDecl *D,
1283 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001284 assert(D);
1285
1286 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001287 Overridden.append(overridden_methods_begin(CXXMethod),
1288 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001289 return;
1290 }
1291
1292 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1293 if (!Method)
1294 return;
1295
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001296 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1297 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001298 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001299}
1300
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001301void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1302 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1303 assert(!Import->isFromASTFile() && "Non-local import declaration");
1304 if (!FirstLocalImport) {
1305 FirstLocalImport = Import;
1306 LastLocalImport = Import;
1307 return;
1308 }
1309
1310 LastLocalImport->NextLocalImport = Import;
1311 LastLocalImport = Import;
1312}
1313
Chris Lattner53cfe802007-07-18 17:52:12 +00001314//===----------------------------------------------------------------------===//
1315// Type Sizing and Analysis
1316//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001317
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001318/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1319/// scalar floating point type.
1320const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001321 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001322 assert(BT && "Not a floating point type!");
1323 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001324 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001325 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001326 case BuiltinType::Float: return Target->getFloatFormat();
1327 case BuiltinType::Double: return Target->getDoubleFormat();
1328 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001329 }
1330}
1331
Rafael Espindola71eccb32013-08-08 19:53:46 +00001332CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001333 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001334
John McCall94268702010-10-08 18:24:19 +00001335 bool UseAlignAttrOnly = false;
1336 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1337 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001338
John McCall94268702010-10-08 18:24:19 +00001339 // __attribute__((aligned)) can increase or decrease alignment
1340 // *except* on a struct or struct member, where it only increases
1341 // alignment unless 'packed' is also specified.
1342 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001343 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001344 // ignore that possibility; Sema should diagnose it.
1345 if (isa<FieldDecl>(D)) {
1346 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1347 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1348 } else {
1349 UseAlignAttrOnly = true;
1350 }
1351 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001352 else if (isa<FieldDecl>(D))
1353 UseAlignAttrOnly =
1354 D->hasAttr<PackedAttr>() ||
1355 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001356
John McCall4e819612011-01-20 07:57:12 +00001357 // If we're using the align attribute only, just ignore everything
1358 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001359 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001360 // do nothing
1361
John McCall94268702010-10-08 18:24:19 +00001362 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001363 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001364 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001365 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001366 T = RT->getPointeeType();
1367 else
1368 T = getPointerType(RT->getPointeeType());
1369 }
Richard Smithf6d70302014-06-10 23:34:28 +00001370 QualType BaseT = getBaseElementType(T);
1371 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001372 // Adjust alignments of declarations with array type by the
1373 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001374 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001375 unsigned MinWidth = Target->getLargeArrayMinWidth();
1376 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001377 if (isa<VariableArrayType>(arrayType))
1378 Align = std::max(Align, Target->getLargeArrayAlign());
1379 else if (isa<ConstantArrayType>(arrayType) &&
1380 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1381 Align = std::max(Align, Target->getLargeArrayAlign());
1382 }
John McCall33ddac02011-01-19 10:06:00 +00001383 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001384 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001385 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001386 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001387 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1388 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001389 }
John McCall4e819612011-01-20 07:57:12 +00001390
1391 // Fields can be subject to extra alignment constraints, like if
1392 // the field is packed, the struct is packed, or the struct has a
1393 // a max-field-alignment constraint (#pragma pack). So calculate
1394 // the actual alignment of the field within the struct, and then
1395 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001396 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1397 const RecordDecl *Parent = Field->getParent();
1398 // We can only produce a sensible answer if the record is valid.
1399 if (!Parent->isInvalidDecl()) {
1400 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001401
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001402 // Start with the record's overall alignment.
1403 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001404
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001405 // Use the GCD of that and the offset within the record.
1406 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1407 if (Offset > 0) {
1408 // Alignment is always a power of 2, so the GCD will be a power of 2,
1409 // which means we get to do this crazy thing instead of Euclid's.
1410 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1411 if (LowBitOfOffset < FieldAlign)
1412 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1413 }
1414
1415 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001416 }
Charles Davis3fc51072010-02-23 04:52:00 +00001417 }
Chris Lattner68061312009-01-24 21:53:27 +00001418 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001419
Ken Dyckcc56c542011-01-15 18:38:59 +00001420 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001421}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001422
John McCallf1249922012-08-21 04:10:00 +00001423// getTypeInfoDataSizeInChars - Return the size of a type, in
1424// chars. If the type is a record, its data size is returned. This is
1425// the size of the memcpy that's performed when assigning this type
1426// using a trivial copy/move assignment operator.
1427std::pair<CharUnits, CharUnits>
1428ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1429 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1430
1431 // In C++, objects can sometimes be allocated into the tail padding
1432 // of a base-class subobject. We decide whether that's possible
1433 // during class layout, so here we can just trust the layout results.
1434 if (getLangOpts().CPlusPlus) {
1435 if (const RecordType *RT = T->getAs<RecordType>()) {
1436 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1437 sizeAndAlign.first = layout.getDataSize();
1438 }
1439 }
1440
1441 return sizeAndAlign;
1442}
1443
Richard Trieu04d2d942013-05-14 21:59:17 +00001444/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1445/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1446std::pair<CharUnits, CharUnits>
1447static getConstantArrayInfoInChars(const ASTContext &Context,
1448 const ConstantArrayType *CAT) {
1449 std::pair<CharUnits, CharUnits> EltInfo =
1450 Context.getTypeInfoInChars(CAT->getElementType());
1451 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001452 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1453 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001454 "Overflow in array type char size evaluation");
1455 uint64_t Width = EltInfo.first.getQuantity() * Size;
1456 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001457 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1458 Context.getTargetInfo().getPointerWidth(0) == 64)
1459 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001460 return std::make_pair(CharUnits::fromQuantity(Width),
1461 CharUnits::fromQuantity(Align));
1462}
1463
John McCall87fe5d52010-05-20 01:18:31 +00001464std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001465ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001466 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1467 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001468 TypeInfo Info = getTypeInfo(T);
1469 return std::make_pair(toCharUnitsFromBits(Info.Width),
1470 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001471}
1472
1473std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001474ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001475 return getTypeInfoInChars(T.getTypePtr());
1476}
1477
David Majnemer34b57492014-07-30 01:30:47 +00001478bool ASTContext::isAlignmentRequired(const Type *T) const {
1479 return getTypeInfo(T).AlignIsRequired;
1480}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001481
David Majnemer34b57492014-07-30 01:30:47 +00001482bool ASTContext::isAlignmentRequired(QualType T) const {
1483 return isAlignmentRequired(T.getTypePtr());
1484}
1485
1486TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001487 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1488 if (I != MemoizedTypeInfo.end())
1489 return I->second;
1490
1491 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1492 TypeInfo TI = getTypeInfoImpl(T);
1493 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001494 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001495}
1496
1497/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1498/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001499///
1500/// FIXME: Pointers into different addr spaces could have different sizes and
1501/// alignment requirements: getPointerInfo should take an AddrSpace, this
1502/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001503TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1504 uint64_t Width = 0;
1505 unsigned Align = 8;
1506 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001507 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001508#define TYPE(Class, Base)
1509#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001510#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001511#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001512#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1513 case Type::Class: \
1514 assert(!T->isDependentType() && "should not see dependent types here"); \
1515 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001516#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001517 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001518
Chris Lattner355332d2007-07-13 22:27:08 +00001519 case Type::FunctionNoProto:
1520 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001521 // GCC extension: alignof(function) = 32 bits
1522 Width = 0;
1523 Align = 32;
1524 break;
1525
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001526 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001527 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001528 Width = 0;
1529 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1530 break;
1531
Steve Naroff5c131802007-08-30 01:06:46 +00001532 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001533 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001534
David Majnemer34b57492014-07-30 01:30:47 +00001535 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001536 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001537 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001538 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001539 Width = EltInfo.Width * Size;
1540 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001541 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1542 getTargetInfo().getPointerWidth(0) == 64)
1543 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001544 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001545 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001546 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001547 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001548 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001549 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1550 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001551 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001552 // If the alignment is not a power of 2, round up to the next power of 2.
1553 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001554 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001555 Align = llvm::NextPowerOf2(Align);
1556 Width = llvm::RoundUpToAlignment(Width, Align);
1557 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001558 // Adjust the alignment based on the target max.
1559 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1560 if (TargetVectorAlign && TargetVectorAlign < Align)
1561 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001562 break;
1563 }
Chris Lattner647fb222007-07-18 18:26:58 +00001564
Chris Lattner7570e9c2008-03-08 08:52:55 +00001565 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001566 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001567 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001568 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001569 // GCC extension: alignof(void) = 8 bits.
1570 Width = 0;
1571 Align = 8;
1572 break;
1573
Chris Lattner6a4f7452007-12-19 19:23:28 +00001574 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001575 Width = Target->getBoolWidth();
1576 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001577 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001578 case BuiltinType::Char_S:
1579 case BuiltinType::Char_U:
1580 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001581 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001582 Width = Target->getCharWidth();
1583 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001584 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001585 case BuiltinType::WChar_S:
1586 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001587 Width = Target->getWCharWidth();
1588 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001589 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001590 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001591 Width = Target->getChar16Width();
1592 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001593 break;
1594 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001595 Width = Target->getChar32Width();
1596 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001597 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001598 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001599 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001600 Width = Target->getShortWidth();
1601 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001602 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001603 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001604 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001605 Width = Target->getIntWidth();
1606 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001607 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001608 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001609 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001610 Width = Target->getLongWidth();
1611 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001612 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001613 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001614 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001615 Width = Target->getLongLongWidth();
1616 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001617 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001618 case BuiltinType::Int128:
1619 case BuiltinType::UInt128:
1620 Width = 128;
1621 Align = 128; // int128_t is 128-bit aligned on all targets.
1622 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001623 case BuiltinType::Half:
1624 Width = Target->getHalfWidth();
1625 Align = Target->getHalfAlign();
1626 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001627 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001628 Width = Target->getFloatWidth();
1629 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001630 break;
1631 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001632 Width = Target->getDoubleWidth();
1633 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001634 break;
1635 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001636 Width = Target->getLongDoubleWidth();
1637 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001638 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001639 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001640 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1641 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001642 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001643 case BuiltinType::ObjCId:
1644 case BuiltinType::ObjCClass:
1645 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001646 Width = Target->getPointerWidth(0);
1647 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001648 break;
Guy Benyei61054192013-02-07 10:55:47 +00001649 case BuiltinType::OCLSampler:
1650 // Samplers are modeled as integers.
1651 Width = Target->getIntWidth();
1652 Align = Target->getIntAlign();
1653 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001654 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001655 case BuiltinType::OCLClkEvent:
1656 case BuiltinType::OCLQueue:
1657 case BuiltinType::OCLNDRange:
1658 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001659 case BuiltinType::OCLImage1d:
1660 case BuiltinType::OCLImage1dArray:
1661 case BuiltinType::OCLImage1dBuffer:
1662 case BuiltinType::OCLImage2d:
1663 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001664 case BuiltinType::OCLImage2dDepth:
1665 case BuiltinType::OCLImage2dArrayDepth:
1666 case BuiltinType::OCLImage2dMSAA:
1667 case BuiltinType::OCLImage2dArrayMSAA:
1668 case BuiltinType::OCLImage2dMSAADepth:
1669 case BuiltinType::OCLImage2dArrayMSAADepth:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001670 case BuiltinType::OCLImage3d:
1671 // Currently these types are pointers to opaque types.
1672 Width = Target->getPointerWidth(0);
1673 Align = Target->getPointerAlign(0);
1674 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001675 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001676 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001677 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001678 Width = Target->getPointerWidth(0);
1679 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001680 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001681 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001682 unsigned AS = getTargetAddressSpace(
1683 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001684 Width = Target->getPointerWidth(AS);
1685 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001686 break;
1687 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001688 case Type::LValueReference:
1689 case Type::RValueReference: {
1690 // alignof and sizeof should never enter this code path here, so we go
1691 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001692 unsigned AS = getTargetAddressSpace(
1693 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001694 Width = Target->getPointerWidth(AS);
1695 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001696 break;
1697 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001698 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001699 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001700 Width = Target->getPointerWidth(AS);
1701 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001702 break;
1703 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001704 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001705 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001706 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001707 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001708 }
Chris Lattner647fb222007-07-18 18:26:58 +00001709 case Type::Complex: {
1710 // Complex types have the same alignment as their elements, but twice the
1711 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001712 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1713 Width = EltInfo.Width * 2;
1714 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001715 break;
1716 }
John McCall8b07ec22010-05-15 11:32:37 +00001717 case Type::ObjCObject:
1718 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001719 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001720 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001721 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001722 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001723 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001724 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001725 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001726 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001727 break;
1728 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001729 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001730 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001731 const TagType *TT = cast<TagType>(T);
1732
1733 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001734 Width = 8;
1735 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001736 break;
1737 }
Mike Stump11289f42009-09-09 15:08:12 +00001738
David Majnemer475b25e2015-01-21 10:54:38 +00001739 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1740 const EnumDecl *ED = ET->getDecl();
1741 TypeInfo Info =
1742 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1743 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1744 Info.Align = AttrAlign;
1745 Info.AlignIsRequired = true;
1746 }
1747 return Info;
1748 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001749
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001750 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001751 const RecordDecl *RD = RT->getDecl();
1752 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001753 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001754 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001755 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001756 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001757 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001758
Chris Lattner63d2b362009-10-22 05:17:15 +00001759 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001760 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1761 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001762
Richard Smith30482bc2011-02-20 03:19:35 +00001763 case Type::Auto: {
1764 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001765 assert(!A->getDeducedType().isNull() &&
1766 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001767 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001768 }
1769
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001770 case Type::Paren:
1771 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1772
Douglas Gregoref462e62009-04-30 17:32:17 +00001773 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001774 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001775 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001776 // If the typedef has an aligned attribute on it, it overrides any computed
1777 // alignment we have. This violates the GCC documentation (which says that
1778 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001779 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001780 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001781 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001782 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001783 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001784 AlignIsRequired = Info.AlignIsRequired;
1785 }
David Majnemer34b57492014-07-30 01:30:47 +00001786 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001787 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001788 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001789
Abramo Bagnara6150c882010-05-11 21:36:43 +00001790 case Type::Elaborated:
1791 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001792
John McCall81904512011-01-06 01:58:22 +00001793 case Type::Attributed:
1794 return getTypeInfo(
1795 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1796
Eli Friedman0dfb8892011-10-06 23:00:33 +00001797 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001798 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001799 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1800 Width = Info.Width;
1801 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001802
1803 // If the size of the type doesn't exceed the platform's max
1804 // atomic promotion width, make the size and alignment more
1805 // favorable to atomic operations:
1806 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1807 // Round the size up to a power of 2.
1808 if (!llvm::isPowerOf2_64(Width))
1809 Width = llvm::NextPowerOf2(Width);
1810
1811 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001812 Align = static_cast<unsigned>(Width);
1813 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001814 }
1815
Douglas Gregoref462e62009-04-30 17:32:17 +00001816 }
Mike Stump11289f42009-09-09 15:08:12 +00001817
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001818 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001819 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001820}
1821
Alexey Bataev00396512015-07-02 03:40:19 +00001822unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1823 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1824 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1825 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1826 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1827 getTargetInfo().getABI() == "elfv1-qpx" &&
1828 T->isSpecificBuiltinType(BuiltinType::Double))
1829 SimdAlign = 256;
1830 return SimdAlign;
1831}
1832
Ken Dyckcc56c542011-01-15 18:38:59 +00001833/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1834CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1835 return CharUnits::fromQuantity(BitSize / getCharWidth());
1836}
1837
Ken Dyckb0fcc592011-02-11 01:54:29 +00001838/// toBits - Convert a size in characters to a size in characters.
1839int64_t ASTContext::toBits(CharUnits CharSize) const {
1840 return CharSize.getQuantity() * getCharWidth();
1841}
1842
Ken Dyck8c89d592009-12-22 14:23:30 +00001843/// getTypeSizeInChars - Return the size of the specified type, in characters.
1844/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001845CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001846 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001847}
Jay Foad39c79802011-01-12 09:06:06 +00001848CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001849 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001850}
1851
Ken Dycka6046ab2010-01-26 17:25:18 +00001852/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001853/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001854CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001855 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001856}
Jay Foad39c79802011-01-12 09:06:06 +00001857CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001858 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001859}
1860
Chris Lattnera3402cd2009-01-27 18:08:34 +00001861/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1862/// type for the current target in bits. This can be different than the ABI
1863/// alignment in cases where it is beneficial for performance to overalign
1864/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001865unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001866 TypeInfo TI = getTypeInfo(T);
1867 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001868
David Majnemere1544562015-04-24 01:25:05 +00001869 T = T->getBaseElementTypeUnsafe();
1870
1871 // The preferred alignment of member pointers is that of a pointer.
1872 if (T->isMemberPointerType())
1873 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1874
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001875 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1876 return ABIAlign; // Never overalign on XCore.
1877
Eli Friedman7ab09572009-05-25 21:27:19 +00001878 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001879 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001880 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001881 if (const EnumType *ET = T->getAs<EnumType>())
1882 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001883 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001884 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1885 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001886 // Don't increase the alignment if an alignment attribute was specified on a
1887 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001888 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001889 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001890
Chris Lattnera3402cd2009-01-27 18:08:34 +00001891 return ABIAlign;
1892}
1893
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001894/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1895/// for __attribute__((aligned)) on this target, to be used if no alignment
1896/// value is specified.
1897unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1898 return getTargetInfo().getDefaultAlignForAttributeAligned();
1899}
1900
Ulrich Weigandfa806422013-05-06 16:23:57 +00001901/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1902/// to a global variable of the specified type.
1903unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1904 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1905}
1906
1907/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1908/// should be given to a global variable of the specified type.
1909CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1910 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1911}
1912
David Majnemer08ef2ba2015-06-23 20:34:18 +00001913CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1914 CharUnits Offset = CharUnits::Zero();
1915 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1916 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1917 Offset += Layout->getBaseClassOffset(Base);
1918 Layout = &getASTRecordLayout(Base);
1919 }
1920 return Offset;
1921}
1922
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001923/// DeepCollectObjCIvars -
1924/// This routine first collects all declared, but not synthesized, ivars in
1925/// super class and then collects all ivars, including those synthesized for
1926/// current class. This routine is used for implementation of current class
1927/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001928///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001929void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1930 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001931 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001932 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1933 DeepCollectObjCIvars(SuperClass, false, Ivars);
1934 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001935 for (const auto *I : OI->ivars())
1936 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001937 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001938 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001939 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001940 Iv= Iv->getNextIvar())
1941 Ivars.push_back(Iv);
1942 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001943}
1944
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001945/// CollectInheritedProtocols - Collect all protocols in current class and
1946/// those inherited by it.
1947void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001948 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001949 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001950 // We can use protocol_iterator here instead of
1951 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001952 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001953 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001954 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001955
1956 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001957 for (const auto *Cat : OI->visible_categories())
1958 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001959
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001960 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1961 while (SD) {
1962 CollectInheritedProtocols(SD, Protocols);
1963 SD = SD->getSuperClass();
1964 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001965 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001966 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001967 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001968 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001969 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001970 // Insert the protocol.
1971 if (!Protocols.insert(
1972 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1973 return;
1974
1975 for (auto *Proto : OP->protocols())
1976 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001977 }
1978}
1979
Jay Foad39c79802011-01-12 09:06:06 +00001980unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001981 unsigned count = 0;
1982 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00001983 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001984 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001985
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001986 // Count ivar defined in this class's implementation. This
1987 // includes synthesized ivars.
1988 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001989 count += ImplDecl->ivar_size();
1990
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001991 return count;
1992}
1993
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001994bool ASTContext::isSentinelNullExpr(const Expr *E) {
1995 if (!E)
1996 return false;
1997
1998 // nullptr_t is always treated as null.
1999 if (E->getType()->isNullPtrType()) return true;
2000
2001 if (E->getType()->isAnyPointerType() &&
2002 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2003 Expr::NPC_ValueDependentIsNull))
2004 return true;
2005
2006 // Unfortunately, __null has type 'int'.
2007 if (isa<GNUNullExpr>(E)) return true;
2008
2009 return false;
2010}
2011
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002012/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2013ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2014 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2015 I = ObjCImpls.find(D);
2016 if (I != ObjCImpls.end())
2017 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002018 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002019}
2020/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2021ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2022 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2023 I = ObjCImpls.find(D);
2024 if (I != ObjCImpls.end())
2025 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002026 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002027}
2028
2029/// \brief Set the implementation of ObjCInterfaceDecl.
2030void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2031 ObjCImplementationDecl *ImplD) {
2032 assert(IFaceD && ImplD && "Passed null params");
2033 ObjCImpls[IFaceD] = ImplD;
2034}
2035/// \brief Set the implementation of ObjCCategoryDecl.
2036void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2037 ObjCCategoryImplDecl *ImplD) {
2038 assert(CatD && ImplD && "Passed null params");
2039 ObjCImpls[CatD] = ImplD;
2040}
2041
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002042const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2043 const NamedDecl *ND) const {
2044 if (const ObjCInterfaceDecl *ID =
2045 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002046 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002047 if (const ObjCCategoryDecl *CD =
2048 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002049 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002050 if (const ObjCImplDecl *IMD =
2051 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002052 return IMD->getClassInterface();
2053
Craig Topper36250ad2014-05-12 05:36:57 +00002054 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002055}
2056
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002057/// \brief Get the copy initialization expression of VarDecl,or NULL if
2058/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002059Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002060 assert(VD && "Passed null params");
2061 assert(VD->hasAttr<BlocksAttr>() &&
2062 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002063 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002064 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002065 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002066}
2067
2068/// \brief Set the copy inialization expression of a block var decl.
2069void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2070 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002071 assert(VD->hasAttr<BlocksAttr>() &&
2072 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002073 BlockVarCopyInits[VD] = Init;
2074}
2075
John McCallbcd03502009-12-07 02:54:59 +00002076TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002077 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002078 if (!DataSize)
2079 DataSize = TypeLoc::getFullDataSizeForType(T);
2080 else
2081 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002082 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002083
John McCallbcd03502009-12-07 02:54:59 +00002084 TypeSourceInfo *TInfo =
2085 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2086 new (TInfo) TypeSourceInfo(T);
2087 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002088}
2089
John McCallbcd03502009-12-07 02:54:59 +00002090TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002091 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002092 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002093 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002094 return DI;
2095}
2096
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002097const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002098ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002099 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002100}
2101
2102const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002103ASTContext::getASTObjCImplementationLayout(
2104 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002105 return getObjCLayout(D->getClassInterface(), D);
2106}
2107
Chris Lattner983a8bb2007-07-13 22:13:22 +00002108//===----------------------------------------------------------------------===//
2109// Type creation/memoization methods
2110//===----------------------------------------------------------------------===//
2111
Jay Foad39c79802011-01-12 09:06:06 +00002112QualType
John McCall33ddac02011-01-19 10:06:00 +00002113ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2114 unsigned fastQuals = quals.getFastQualifiers();
2115 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002116
2117 // Check if we've already instantiated this type.
2118 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002119 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002120 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002121 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2122 assert(eq->getQualifiers() == quals);
2123 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002124 }
2125
John McCall33ddac02011-01-19 10:06:00 +00002126 // If the base type is not canonical, make the appropriate canonical type.
2127 QualType canon;
2128 if (!baseType->isCanonicalUnqualified()) {
2129 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002130 canonSplit.Quals.addConsistentQualifiers(quals);
2131 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002132
2133 // Re-find the insert position.
2134 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2135 }
2136
2137 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2138 ExtQualNodes.InsertNode(eq, insertPos);
2139 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002140}
2141
Jay Foad39c79802011-01-12 09:06:06 +00002142QualType
2143ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002144 QualType CanT = getCanonicalType(T);
2145 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002146 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002147
John McCall8ccfcb52009-09-24 19:53:00 +00002148 // If we are composing extended qualifiers together, merge together
2149 // into one ExtQuals node.
2150 QualifierCollector Quals;
2151 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002152
John McCall8ccfcb52009-09-24 19:53:00 +00002153 // If this type already has an address space specified, it cannot get
2154 // another one.
2155 assert(!Quals.hasAddressSpace() &&
2156 "Type cannot be in multiple addr spaces!");
2157 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002158
John McCall8ccfcb52009-09-24 19:53:00 +00002159 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002160}
2161
Chris Lattnerd60183d2009-02-18 22:53:11 +00002162QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002163 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002164 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002165 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002166 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002167
John McCall53fa7142010-12-24 02:08:15 +00002168 if (const PointerType *ptr = T->getAs<PointerType>()) {
2169 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002170 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002171 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2172 return getPointerType(ResultType);
2173 }
2174 }
Mike Stump11289f42009-09-09 15:08:12 +00002175
John McCall8ccfcb52009-09-24 19:53:00 +00002176 // If we are composing extended qualifiers together, merge together
2177 // into one ExtQuals node.
2178 QualifierCollector Quals;
2179 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002180
John McCall8ccfcb52009-09-24 19:53:00 +00002181 // If this type already has an ObjCGC specified, it cannot get
2182 // another one.
2183 assert(!Quals.hasObjCGCAttr() &&
2184 "Type cannot have multiple ObjCGCs!");
2185 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002186
John McCall8ccfcb52009-09-24 19:53:00 +00002187 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002188}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002189
John McCall4f5019e2010-12-19 02:44:49 +00002190const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2191 FunctionType::ExtInfo Info) {
2192 if (T->getExtInfo() == Info)
2193 return T;
2194
2195 QualType Result;
2196 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002197 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002198 } else {
2199 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2200 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2201 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002202 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002203 }
2204
2205 return cast<FunctionType>(Result.getTypePtr());
2206}
2207
Richard Smith2a7d4812013-05-04 07:00:32 +00002208void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2209 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002210 FD = FD->getMostRecentDecl();
2211 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002212 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2213 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002214 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002215 if (FunctionDecl *Next = FD->getPreviousDecl())
2216 FD = Next;
2217 else
2218 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002219 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002220 if (ASTMutationListener *L = getASTMutationListener())
2221 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002222}
2223
Richard Smith0b3a4622014-11-13 20:01:57 +00002224/// Get a function type and produce the equivalent function type with the
2225/// specified exception specification. Type sugar that can be present on a
2226/// declaration of a function with an exception specification is permitted
2227/// and preserved. Other type sugar (for instance, typedefs) is not.
2228static QualType getFunctionTypeWithExceptionSpec(
2229 ASTContext &Context, QualType Orig,
2230 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2231 // Might have some parens.
2232 if (auto *PT = dyn_cast<ParenType>(Orig))
2233 return Context.getParenType(
2234 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2235
2236 // Might have a calling-convention attribute.
2237 if (auto *AT = dyn_cast<AttributedType>(Orig))
2238 return Context.getAttributedType(
2239 AT->getAttrKind(),
2240 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2241 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2242 ESI));
2243
2244 // Anything else must be a function type. Rebuild it with the new exception
2245 // specification.
2246 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2247 return Context.getFunctionType(
2248 Proto->getReturnType(), Proto->getParamTypes(),
2249 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2250}
2251
2252void ASTContext::adjustExceptionSpec(
2253 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2254 bool AsWritten) {
2255 // Update the type.
2256 QualType Updated =
2257 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2258 FD->setType(Updated);
2259
2260 if (!AsWritten)
2261 return;
2262
2263 // Update the type in the type source information too.
2264 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2265 // If the type and the type-as-written differ, we may need to update
2266 // the type-as-written too.
2267 if (TSInfo->getType() != FD->getType())
2268 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2269
2270 // FIXME: When we get proper type location information for exceptions,
2271 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2272 // up the TypeSourceInfo;
2273 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2274 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2275 "TypeLoc size mismatch from updating exception specification");
2276 TSInfo->overrideType(Updated);
2277 }
2278}
2279
Chris Lattnerc6395932007-06-22 20:56:16 +00002280/// getComplexType - Return the uniqued reference to the type for a complex
2281/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002282QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002283 // Unique pointers, to guarantee there is only one pointer of a particular
2284 // structure.
2285 llvm::FoldingSetNodeID ID;
2286 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002287
Craig Topper36250ad2014-05-12 05:36:57 +00002288 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002289 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2290 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002291
Chris Lattnerc6395932007-06-22 20:56:16 +00002292 // If the pointee type isn't canonical, this won't be a canonical type either,
2293 // so fill in the canonical type field.
2294 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002295 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002296 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002297
Chris Lattnerc6395932007-06-22 20:56:16 +00002298 // Get the new insert position for the node we care about.
2299 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002300 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002301 }
John McCall90d1c2d2009-09-24 23:30:46 +00002302 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002303 Types.push_back(New);
2304 ComplexTypes.InsertNode(New, InsertPos);
2305 return QualType(New, 0);
2306}
2307
Chris Lattner970e54e2006-11-12 00:37:36 +00002308/// getPointerType - Return the uniqued reference to the type for a pointer to
2309/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002310QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002311 // Unique pointers, to guarantee there is only one pointer of a particular
2312 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002313 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002314 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002315
Craig Topper36250ad2014-05-12 05:36:57 +00002316 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002317 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002318 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002319
Chris Lattner7ccecb92006-11-12 08:50:50 +00002320 // If the pointee type isn't canonical, this won't be a canonical type either,
2321 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002322 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002323 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002324 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002325
Bob Wilsonc8541f22013-03-15 17:12:43 +00002326 // Get the new insert position for the node we care about.
2327 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002328 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002329 }
John McCall90d1c2d2009-09-24 23:30:46 +00002330 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002331 Types.push_back(New);
2332 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002333 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002334}
2335
Reid Kleckner0503a872013-12-05 01:23:43 +00002336QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2337 llvm::FoldingSetNodeID ID;
2338 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002339 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002340 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2341 if (AT)
2342 return QualType(AT, 0);
2343
2344 QualType Canonical = getCanonicalType(New);
2345
2346 // Get the new insert position for the node we care about.
2347 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002348 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002349
2350 AT = new (*this, TypeAlignment)
2351 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2352 Types.push_back(AT);
2353 AdjustedTypes.InsertNode(AT, InsertPos);
2354 return QualType(AT, 0);
2355}
2356
Reid Kleckner8a365022013-06-24 17:51:48 +00002357QualType ASTContext::getDecayedType(QualType T) const {
2358 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2359
Reid Kleckner8a365022013-06-24 17:51:48 +00002360 QualType Decayed;
2361
2362 // C99 6.7.5.3p7:
2363 // A declaration of a parameter as "array of type" shall be
2364 // adjusted to "qualified pointer to type", where the type
2365 // qualifiers (if any) are those specified within the [ and ] of
2366 // the array type derivation.
2367 if (T->isArrayType())
2368 Decayed = getArrayDecayedType(T);
2369
2370 // C99 6.7.5.3p8:
2371 // A declaration of a parameter as "function returning type"
2372 // shall be adjusted to "pointer to function returning type", as
2373 // in 6.3.2.1.
2374 if (T->isFunctionType())
2375 Decayed = getPointerType(T);
2376
Reid Kleckner0503a872013-12-05 01:23:43 +00002377 llvm::FoldingSetNodeID ID;
2378 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002379 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002380 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2381 if (AT)
2382 return QualType(AT, 0);
2383
Reid Kleckner8a365022013-06-24 17:51:48 +00002384 QualType Canonical = getCanonicalType(Decayed);
2385
2386 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002387 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002388 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002389
Reid Kleckner0503a872013-12-05 01:23:43 +00002390 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2391 Types.push_back(AT);
2392 AdjustedTypes.InsertNode(AT, InsertPos);
2393 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002394}
2395
Mike Stump11289f42009-09-09 15:08:12 +00002396/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002397/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002398QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002399 assert(T->isFunctionType() && "block of function types only");
2400 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002401 // structure.
2402 llvm::FoldingSetNodeID ID;
2403 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002404
Craig Topper36250ad2014-05-12 05:36:57 +00002405 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002406 if (BlockPointerType *PT =
2407 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2408 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002409
2410 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002411 // type either so fill in the canonical type field.
2412 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002413 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002414 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002415
Steve Naroffec33ed92008-08-27 16:04:49 +00002416 // Get the new insert position for the node we care about.
2417 BlockPointerType *NewIP =
2418 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002419 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002420 }
John McCall90d1c2d2009-09-24 23:30:46 +00002421 BlockPointerType *New
2422 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002423 Types.push_back(New);
2424 BlockPointerTypes.InsertNode(New, InsertPos);
2425 return QualType(New, 0);
2426}
2427
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002428/// getLValueReferenceType - Return the uniqued reference to the type for an
2429/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002430QualType
2431ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002432 assert(getCanonicalType(T) != OverloadTy &&
2433 "Unresolved overloaded function type");
2434
Bill Wendling3708c182007-05-27 10:15:43 +00002435 // Unique pointers, to guarantee there is only one pointer of a particular
2436 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002437 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002438 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002439
Craig Topper36250ad2014-05-12 05:36:57 +00002440 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002441 if (LValueReferenceType *RT =
2442 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002443 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002444
John McCallfc93cf92009-10-22 22:37:11 +00002445 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2446
Bill Wendling3708c182007-05-27 10:15:43 +00002447 // If the referencee type isn't canonical, this won't be a canonical type
2448 // either, so fill in the canonical type field.
2449 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002450 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2451 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2452 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002453
Bill Wendling3708c182007-05-27 10:15:43 +00002454 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002455 LValueReferenceType *NewIP =
2456 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002457 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002458 }
2459
John McCall90d1c2d2009-09-24 23:30:46 +00002460 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002461 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2462 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002463 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002464 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002465
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002466 return QualType(New, 0);
2467}
2468
2469/// getRValueReferenceType - Return the uniqued reference to the type for an
2470/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002471QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002472 // Unique pointers, to guarantee there is only one pointer of a particular
2473 // structure.
2474 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002475 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002476
Craig Topper36250ad2014-05-12 05:36:57 +00002477 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002478 if (RValueReferenceType *RT =
2479 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2480 return QualType(RT, 0);
2481
John McCallfc93cf92009-10-22 22:37:11 +00002482 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2483
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002484 // If the referencee type isn't canonical, this won't be a canonical type
2485 // either, so fill in the canonical type field.
2486 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002487 if (InnerRef || !T.isCanonical()) {
2488 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2489 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002490
2491 // Get the new insert position for the node we care about.
2492 RValueReferenceType *NewIP =
2493 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002494 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002495 }
2496
John McCall90d1c2d2009-09-24 23:30:46 +00002497 RValueReferenceType *New
2498 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002499 Types.push_back(New);
2500 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002501 return QualType(New, 0);
2502}
2503
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002504/// getMemberPointerType - Return the uniqued reference to the type for a
2505/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002506QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002507 // Unique pointers, to guarantee there is only one pointer of a particular
2508 // structure.
2509 llvm::FoldingSetNodeID ID;
2510 MemberPointerType::Profile(ID, T, Cls);
2511
Craig Topper36250ad2014-05-12 05:36:57 +00002512 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002513 if (MemberPointerType *PT =
2514 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2515 return QualType(PT, 0);
2516
2517 // If the pointee or class type isn't canonical, this won't be a canonical
2518 // type either, so fill in the canonical type field.
2519 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002520 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002521 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2522
2523 // Get the new insert position for the node we care about.
2524 MemberPointerType *NewIP =
2525 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002526 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002527 }
John McCall90d1c2d2009-09-24 23:30:46 +00002528 MemberPointerType *New
2529 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002530 Types.push_back(New);
2531 MemberPointerTypes.InsertNode(New, InsertPos);
2532 return QualType(New, 0);
2533}
2534
Mike Stump11289f42009-09-09 15:08:12 +00002535/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002536/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002537QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002538 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002539 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002540 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002541 assert((EltTy->isDependentType() ||
2542 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002543 "Constant array of VLAs is illegal!");
2544
Chris Lattnere2df3f92009-05-13 04:12:56 +00002545 // Convert the array size into a canonical width matching the pointer size for
2546 // the target.
2547 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002548 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002549 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002550
Chris Lattner23b7eb62007-06-15 23:05:46 +00002551 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002552 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002553
Craig Topper36250ad2014-05-12 05:36:57 +00002554 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002555 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002556 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002557 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002558
John McCall33ddac02011-01-19 10:06:00 +00002559 // If the element type isn't canonical or has qualifiers, this won't
2560 // be a canonical type either, so fill in the canonical type field.
2561 QualType Canon;
2562 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2563 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002564 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002565 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002566 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002567
Chris Lattner36f8e652007-01-27 08:31:04 +00002568 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002569 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002570 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002571 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002572 }
Mike Stump11289f42009-09-09 15:08:12 +00002573
John McCall90d1c2d2009-09-24 23:30:46 +00002574 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002575 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002576 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002577 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002578 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002579}
2580
John McCall06549462011-01-18 08:40:38 +00002581/// getVariableArrayDecayedType - Turns the given type, which may be
2582/// variably-modified, into the corresponding type with all the known
2583/// sizes replaced with [*].
2584QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2585 // Vastly most common case.
2586 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002587
John McCall06549462011-01-18 08:40:38 +00002588 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002589
John McCall06549462011-01-18 08:40:38 +00002590 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002591 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002592 switch (ty->getTypeClass()) {
2593#define TYPE(Class, Base)
2594#define ABSTRACT_TYPE(Class, Base)
2595#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2596#include "clang/AST/TypeNodes.def"
2597 llvm_unreachable("didn't desugar past all non-canonical types?");
2598
2599 // These types should never be variably-modified.
2600 case Type::Builtin:
2601 case Type::Complex:
2602 case Type::Vector:
2603 case Type::ExtVector:
2604 case Type::DependentSizedExtVector:
2605 case Type::ObjCObject:
2606 case Type::ObjCInterface:
2607 case Type::ObjCObjectPointer:
2608 case Type::Record:
2609 case Type::Enum:
2610 case Type::UnresolvedUsing:
2611 case Type::TypeOfExpr:
2612 case Type::TypeOf:
2613 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002614 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002615 case Type::DependentName:
2616 case Type::InjectedClassName:
2617 case Type::TemplateSpecialization:
2618 case Type::DependentTemplateSpecialization:
2619 case Type::TemplateTypeParm:
2620 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002621 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002622 case Type::PackExpansion:
2623 llvm_unreachable("type should never be variably-modified");
2624
2625 // These types can be variably-modified but should never need to
2626 // further decay.
2627 case Type::FunctionNoProto:
2628 case Type::FunctionProto:
2629 case Type::BlockPointer:
2630 case Type::MemberPointer:
2631 return type;
2632
2633 // These types can be variably-modified. All these modifications
2634 // preserve structure except as noted by comments.
2635 // TODO: if we ever care about optimizing VLAs, there are no-op
2636 // optimizations available here.
2637 case Type::Pointer:
2638 result = getPointerType(getVariableArrayDecayedType(
2639 cast<PointerType>(ty)->getPointeeType()));
2640 break;
2641
2642 case Type::LValueReference: {
2643 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2644 result = getLValueReferenceType(
2645 getVariableArrayDecayedType(lv->getPointeeType()),
2646 lv->isSpelledAsLValue());
2647 break;
2648 }
2649
2650 case Type::RValueReference: {
2651 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2652 result = getRValueReferenceType(
2653 getVariableArrayDecayedType(lv->getPointeeType()));
2654 break;
2655 }
2656
Eli Friedman0dfb8892011-10-06 23:00:33 +00002657 case Type::Atomic: {
2658 const AtomicType *at = cast<AtomicType>(ty);
2659 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2660 break;
2661 }
2662
John McCall06549462011-01-18 08:40:38 +00002663 case Type::ConstantArray: {
2664 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2665 result = getConstantArrayType(
2666 getVariableArrayDecayedType(cat->getElementType()),
2667 cat->getSize(),
2668 cat->getSizeModifier(),
2669 cat->getIndexTypeCVRQualifiers());
2670 break;
2671 }
2672
2673 case Type::DependentSizedArray: {
2674 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2675 result = getDependentSizedArrayType(
2676 getVariableArrayDecayedType(dat->getElementType()),
2677 dat->getSizeExpr(),
2678 dat->getSizeModifier(),
2679 dat->getIndexTypeCVRQualifiers(),
2680 dat->getBracketsRange());
2681 break;
2682 }
2683
2684 // Turn incomplete types into [*] types.
2685 case Type::IncompleteArray: {
2686 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2687 result = getVariableArrayType(
2688 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002689 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002690 ArrayType::Normal,
2691 iat->getIndexTypeCVRQualifiers(),
2692 SourceRange());
2693 break;
2694 }
2695
2696 // Turn VLA types into [*] types.
2697 case Type::VariableArray: {
2698 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2699 result = getVariableArrayType(
2700 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002701 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002702 ArrayType::Star,
2703 vat->getIndexTypeCVRQualifiers(),
2704 vat->getBracketsRange());
2705 break;
2706 }
2707 }
2708
2709 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002710 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002711}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002712
Steve Naroffcadebd02007-08-30 18:14:25 +00002713/// getVariableArrayType - Returns a non-unique reference to the type for a
2714/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002715QualType ASTContext::getVariableArrayType(QualType EltTy,
2716 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002717 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002718 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002719 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002720 // Since we don't unique expressions, it isn't possible to unique VLA's
2721 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002722 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002723
John McCall33ddac02011-01-19 10:06:00 +00002724 // Be sure to pull qualifiers off the element type.
2725 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2726 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002727 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002728 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002729 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002730 }
2731
John McCall90d1c2d2009-09-24 23:30:46 +00002732 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002733 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002734
2735 VariableArrayTypes.push_back(New);
2736 Types.push_back(New);
2737 return QualType(New, 0);
2738}
2739
Douglas Gregor4619e432008-12-05 23:32:09 +00002740/// getDependentSizedArrayType - Returns a non-unique reference to
2741/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002742/// type.
John McCall33ddac02011-01-19 10:06:00 +00002743QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2744 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002745 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002746 unsigned elementTypeQuals,
2747 SourceRange brackets) const {
2748 assert((!numElements || numElements->isTypeDependent() ||
2749 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002750 "Size must be type- or value-dependent!");
2751
John McCall33ddac02011-01-19 10:06:00 +00002752 // Dependently-sized array types that do not have a specified number
2753 // of elements will have their sizes deduced from a dependent
2754 // initializer. We do no canonicalization here at all, which is okay
2755 // because they can't be used in most locations.
2756 if (!numElements) {
2757 DependentSizedArrayType *newType
2758 = new (*this, TypeAlignment)
2759 DependentSizedArrayType(*this, elementType, QualType(),
2760 numElements, ASM, elementTypeQuals,
2761 brackets);
2762 Types.push_back(newType);
2763 return QualType(newType, 0);
2764 }
2765
2766 // Otherwise, we actually build a new type every time, but we
2767 // also build a canonical type.
2768
2769 SplitQualType canonElementType = getCanonicalType(elementType).split();
2770
Craig Topper36250ad2014-05-12 05:36:57 +00002771 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002772 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002773 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002774 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002775 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002776
John McCall33ddac02011-01-19 10:06:00 +00002777 // Look for an existing type with these properties.
2778 DependentSizedArrayType *canonTy =
2779 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002780
John McCall33ddac02011-01-19 10:06:00 +00002781 // If we don't have one, build one.
2782 if (!canonTy) {
2783 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002784 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002785 QualType(), numElements, ASM, elementTypeQuals,
2786 brackets);
2787 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2788 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002789 }
2790
John McCall33ddac02011-01-19 10:06:00 +00002791 // Apply qualifiers from the element type to the array.
2792 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002793 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002794
David Majnemer16a74702015-07-24 05:54:19 +00002795 // If we didn't need extra canonicalization for the element type or the size
2796 // expression, then just use that as our result.
2797 if (QualType(canonElementType.Ty, 0) == elementType &&
2798 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002799 return canon;
2800
2801 // Otherwise, we need to build a type which follows the spelling
2802 // of the element type.
2803 DependentSizedArrayType *sugaredType
2804 = new (*this, TypeAlignment)
2805 DependentSizedArrayType(*this, elementType, canon, numElements,
2806 ASM, elementTypeQuals, brackets);
2807 Types.push_back(sugaredType);
2808 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002809}
2810
John McCall33ddac02011-01-19 10:06:00 +00002811QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002812 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002813 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002814 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002815 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002816
Craig Topper36250ad2014-05-12 05:36:57 +00002817 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002818 if (IncompleteArrayType *iat =
2819 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2820 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002821
2822 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002823 // either, so fill in the canonical type field. We also have to pull
2824 // qualifiers off the element type.
2825 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002826
John McCall33ddac02011-01-19 10:06:00 +00002827 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2828 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002829 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002830 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002831 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002832
2833 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002834 IncompleteArrayType *existing =
2835 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2836 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002837 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002838
John McCall33ddac02011-01-19 10:06:00 +00002839 IncompleteArrayType *newType = new (*this, TypeAlignment)
2840 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002841
John McCall33ddac02011-01-19 10:06:00 +00002842 IncompleteArrayTypes.InsertNode(newType, insertPos);
2843 Types.push_back(newType);
2844 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002845}
2846
Steve Naroff91fcddb2007-07-18 18:00:27 +00002847/// getVectorType - Return the unique reference to a vector type of
2848/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002849QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002850 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002851 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002852
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002853 // Check if we've already instantiated a vector of this type.
2854 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002855 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002856
Craig Topper36250ad2014-05-12 05:36:57 +00002857 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002858 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2859 return QualType(VTP, 0);
2860
2861 // If the element type isn't canonical, this won't be a canonical type either,
2862 // so fill in the canonical type field.
2863 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002864 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002865 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002866
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002867 // Get the new insert position for the node we care about.
2868 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002869 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002870 }
John McCall90d1c2d2009-09-24 23:30:46 +00002871 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002872 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002873 VectorTypes.InsertNode(New, InsertPos);
2874 Types.push_back(New);
2875 return QualType(New, 0);
2876}
2877
Nate Begemance4d7fc2008-04-18 23:10:10 +00002878/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002879/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002880QualType
2881ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002882 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002883
Steve Naroff91fcddb2007-07-18 18:00:27 +00002884 // Check if we've already instantiated a vector of this type.
2885 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002886 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002887 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002888 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002889 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2890 return QualType(VTP, 0);
2891
2892 // If the element type isn't canonical, this won't be a canonical type either,
2893 // so fill in the canonical type field.
2894 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002895 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002896 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002897
Steve Naroff91fcddb2007-07-18 18:00:27 +00002898 // Get the new insert position for the node we care about.
2899 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002900 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002901 }
John McCall90d1c2d2009-09-24 23:30:46 +00002902 ExtVectorType *New = new (*this, TypeAlignment)
2903 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002904 VectorTypes.InsertNode(New, InsertPos);
2905 Types.push_back(New);
2906 return QualType(New, 0);
2907}
2908
Jay Foad39c79802011-01-12 09:06:06 +00002909QualType
2910ASTContext::getDependentSizedExtVectorType(QualType vecType,
2911 Expr *SizeExpr,
2912 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002913 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002914 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002915 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002916
Craig Topper36250ad2014-05-12 05:36:57 +00002917 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002918 DependentSizedExtVectorType *Canon
2919 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2920 DependentSizedExtVectorType *New;
2921 if (Canon) {
2922 // We already have a canonical version of this array type; use it as
2923 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002924 New = new (*this, TypeAlignment)
2925 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2926 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002927 } else {
2928 QualType CanonVecTy = getCanonicalType(vecType);
2929 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002930 New = new (*this, TypeAlignment)
2931 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2932 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002933
2934 DependentSizedExtVectorType *CanonCheck
2935 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2936 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2937 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002938 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2939 } else {
2940 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2941 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002942 New = new (*this, TypeAlignment)
2943 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002944 }
2945 }
Mike Stump11289f42009-09-09 15:08:12 +00002946
Douglas Gregor758a8692009-06-17 21:51:59 +00002947 Types.push_back(New);
2948 return QualType(New, 0);
2949}
2950
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002951/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002952///
Jay Foad39c79802011-01-12 09:06:06 +00002953QualType
2954ASTContext::getFunctionNoProtoType(QualType ResultTy,
2955 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002956 const CallingConv CallConv = Info.getCC();
2957
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002958 // Unique functions, to guarantee there is only one function of a particular
2959 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002960 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002961 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002962
Craig Topper36250ad2014-05-12 05:36:57 +00002963 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002964 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002965 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002966 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002967
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002968 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002969 if (!ResultTy.isCanonical()) {
2970 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002971
Chris Lattner47955de2007-01-27 08:37:20 +00002972 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002973 FunctionNoProtoType *NewIP =
2974 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002975 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002976 }
Mike Stump11289f42009-09-09 15:08:12 +00002977
Roman Divacky65b88cd2011-03-01 17:40:53 +00002978 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002979 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002980 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002981 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002982 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002983 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002984}
2985
Douglas Gregorcd780372013-01-17 23:36:45 +00002986/// \brief Determine whether \p T is canonical as the result type of a function.
2987static bool isCanonicalResultType(QualType T) {
2988 return T.isCanonical() &&
2989 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2990 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2991}
2992
Jay Foad39c79802011-01-12 09:06:06 +00002993QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002994ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002995 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002996 size_t NumArgs = ArgArray.size();
2997
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002998 // Unique functions, to guarantee there is only one function of a particular
2999 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003000 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003001 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3002 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003003
Craig Topper36250ad2014-05-12 05:36:57 +00003004 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003005 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003006 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003007 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003008
3009 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003010 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003011 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003012 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003013 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003014 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003015 isCanonical = false;
3016
3017 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003018 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003019 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003020 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003021 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003022 CanonicalArgs.reserve(NumArgs);
3023 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003024 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003025
John McCalldb40c7f2010-12-14 08:05:40 +00003026 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003027 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003028 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003029
Douglas Gregorcd780372013-01-17 23:36:45 +00003030 // Result types do not have ARC lifetime qualifiers.
3031 QualType CanResultTy = getCanonicalType(ResultTy);
3032 if (ResultTy.getQualifiers().hasObjCLifetime()) {
3033 Qualifiers Qs = CanResultTy.getQualifiers();
3034 Qs.removeObjCLifetime();
3035 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
3036 }
3037
Jordan Rose5c382722013-03-08 21:51:21 +00003038 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003039
Chris Lattnerfd4de792007-01-27 01:15:32 +00003040 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003041 FunctionProtoType *NewIP =
3042 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003043 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003044 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003045
John McCall31168b02011-06-15 23:02:42 +00003046 // FunctionProtoType objects are allocated with extra bytes after
3047 // them for three variable size arrays at the end:
3048 // - parameter types
3049 // - exception types
3050 // - consumed-arguments flags
3051 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003052 // expression, or information used to resolve the exception
3053 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003054 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003055 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003056 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3057 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3058 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003059 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003060 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003061 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003062 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003063 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003064 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003065 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003066 Size += NumArgs * sizeof(bool);
3067
John McCalldb40c7f2010-12-14 08:05:40 +00003068 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003069 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003070 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003071 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003072 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003073 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003074}
Chris Lattneref51c202006-11-10 07:17:23 +00003075
John McCalle78aac42010-03-10 03:28:59 +00003076#ifndef NDEBUG
3077static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3078 if (!isa<CXXRecordDecl>(D)) return false;
3079 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3080 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3081 return true;
3082 if (RD->getDescribedClassTemplate() &&
3083 !isa<ClassTemplateSpecializationDecl>(RD))
3084 return true;
3085 return false;
3086}
3087#endif
3088
3089/// getInjectedClassNameType - Return the unique reference to the
3090/// injected class name type for the specified templated declaration.
3091QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003092 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003093 assert(NeedsInjectedClassNameType(Decl));
3094 if (Decl->TypeForDecl) {
3095 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003096 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003097 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3098 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3099 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3100 } else {
John McCall424cec92011-01-19 06:33:43 +00003101 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003102 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003103 Decl->TypeForDecl = newType;
3104 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003105 }
3106 return QualType(Decl->TypeForDecl, 0);
3107}
3108
Douglas Gregor83a586e2008-04-13 21:07:44 +00003109/// getTypeDeclType - Return the unique reference to the type for the
3110/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003111QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003112 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003113 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003114
Richard Smithdda56e42011-04-15 14:24:37 +00003115 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003116 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003117
John McCall96f0b5f2010-03-10 06:48:02 +00003118 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3119 "Template type parameter types are always available.");
3120
John McCall81e38502010-02-16 03:57:14 +00003121 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003122 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003123 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003124 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003125 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003126 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003127 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003128 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003129 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003130 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3131 Decl->TypeForDecl = newType;
3132 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003133 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003134 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003135
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003136 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003137}
3138
Chris Lattner32d920b2007-01-26 02:01:53 +00003139/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003140/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003141QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003142ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3143 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003144 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003145
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003146 if (Canonical.isNull())
3147 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003148 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003149 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003150 Decl->TypeForDecl = newType;
3151 Types.push_back(newType);
3152 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003153}
3154
Jay Foad39c79802011-01-12 09:06:06 +00003155QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003156 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3157
Douglas Gregorec9fd132012-01-14 16:38:05 +00003158 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003159 if (PrevDecl->TypeForDecl)
3160 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3161
John McCall424cec92011-01-19 06:33:43 +00003162 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3163 Decl->TypeForDecl = newType;
3164 Types.push_back(newType);
3165 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003166}
3167
Jay Foad39c79802011-01-12 09:06:06 +00003168QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003169 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3170
Douglas Gregorec9fd132012-01-14 16:38:05 +00003171 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003172 if (PrevDecl->TypeForDecl)
3173 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3174
John McCall424cec92011-01-19 06:33:43 +00003175 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3176 Decl->TypeForDecl = newType;
3177 Types.push_back(newType);
3178 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003179}
3180
John McCall81904512011-01-06 01:58:22 +00003181QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3182 QualType modifiedType,
3183 QualType equivalentType) {
3184 llvm::FoldingSetNodeID id;
3185 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3186
Craig Topper36250ad2014-05-12 05:36:57 +00003187 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003188 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3189 if (type) return QualType(type, 0);
3190
3191 QualType canon = getCanonicalType(equivalentType);
3192 type = new (*this, TypeAlignment)
3193 AttributedType(canon, attrKind, modifiedType, equivalentType);
3194
3195 Types.push_back(type);
3196 AttributedTypes.InsertNode(type, insertPos);
3197
3198 return QualType(type, 0);
3199}
3200
3201
John McCallcebee162009-10-18 09:09:24 +00003202/// \brief Retrieve a substitution-result type.
3203QualType
3204ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003205 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003206 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003207 && "replacement types must always be canonical");
3208
3209 llvm::FoldingSetNodeID ID;
3210 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003211 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003212 SubstTemplateTypeParmType *SubstParm
3213 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3214
3215 if (!SubstParm) {
3216 SubstParm = new (*this, TypeAlignment)
3217 SubstTemplateTypeParmType(Parm, Replacement);
3218 Types.push_back(SubstParm);
3219 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3220 }
3221
3222 return QualType(SubstParm, 0);
3223}
3224
Douglas Gregorada4b792011-01-14 02:55:32 +00003225/// \brief Retrieve a
3226QualType ASTContext::getSubstTemplateTypeParmPackType(
3227 const TemplateTypeParmType *Parm,
3228 const TemplateArgument &ArgPack) {
3229#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003230 for (const auto &P : ArgPack.pack_elements()) {
3231 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3232 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003233 }
3234#endif
3235
3236 llvm::FoldingSetNodeID ID;
3237 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003238 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003239 if (SubstTemplateTypeParmPackType *SubstParm
3240 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3241 return QualType(SubstParm, 0);
3242
3243 QualType Canon;
3244 if (!Parm->isCanonicalUnqualified()) {
3245 Canon = getCanonicalType(QualType(Parm, 0));
3246 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3247 ArgPack);
3248 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3249 }
3250
3251 SubstTemplateTypeParmPackType *SubstParm
3252 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3253 ArgPack);
3254 Types.push_back(SubstParm);
3255 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3256 return QualType(SubstParm, 0);
3257}
3258
Douglas Gregoreff93e02009-02-05 23:33:38 +00003259/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003260/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003261/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003262QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003263 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003264 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003265 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003266 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003267 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003268 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003269 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3270
3271 if (TypeParm)
3272 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003273
Chandler Carruth08836322011-05-01 00:51:33 +00003274 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003275 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003276 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003277
3278 TemplateTypeParmType *TypeCheck
3279 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3280 assert(!TypeCheck && "Template type parameter canonical type broken");
3281 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003282 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003283 TypeParm = new (*this, TypeAlignment)
3284 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003285
3286 Types.push_back(TypeParm);
3287 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3288
3289 return QualType(TypeParm, 0);
3290}
3291
John McCalle78aac42010-03-10 03:28:59 +00003292TypeSourceInfo *
3293ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3294 SourceLocation NameLoc,
3295 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003296 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003297 assert(!Name.getAsDependentTemplateName() &&
3298 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003299 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003300
3301 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003302 TemplateSpecializationTypeLoc TL =
3303 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003304 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003305 TL.setTemplateNameLoc(NameLoc);
3306 TL.setLAngleLoc(Args.getLAngleLoc());
3307 TL.setRAngleLoc(Args.getRAngleLoc());
3308 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3309 TL.setArgLocInfo(i, Args[i].getLocInfo());
3310 return DI;
3311}
3312
Mike Stump11289f42009-09-09 15:08:12 +00003313QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003314ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003315 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003316 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003317 assert(!Template.getAsDependentTemplateName() &&
3318 "No dependent template names here!");
3319
John McCall6b51f282009-11-23 01:53:49 +00003320 unsigned NumArgs = Args.size();
3321
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003322 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003323 ArgVec.reserve(NumArgs);
3324 for (unsigned i = 0; i != NumArgs; ++i)
3325 ArgVec.push_back(Args[i].getArgument());
3326
John McCall2408e322010-04-27 00:57:59 +00003327 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003328 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003329}
3330
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003331#ifndef NDEBUG
3332static bool hasAnyPackExpansions(const TemplateArgument *Args,
3333 unsigned NumArgs) {
3334 for (unsigned I = 0; I != NumArgs; ++I)
3335 if (Args[I].isPackExpansion())
3336 return true;
3337
3338 return true;
3339}
3340#endif
3341
John McCall0ad16662009-10-29 08:12:44 +00003342QualType
3343ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003344 const TemplateArgument *Args,
3345 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003346 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003347 assert(!Template.getAsDependentTemplateName() &&
3348 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003349 // Look through qualified template names.
3350 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3351 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003352
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003353 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003354 Template.getAsTemplateDecl() &&
3355 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003356 QualType CanonType;
3357 if (!Underlying.isNull())
3358 CanonType = getCanonicalType(Underlying);
3359 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003360 // We can get here with an alias template when the specialization contains
3361 // a pack expansion that does not match up with a parameter pack.
3362 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3363 "Caller must compute aliased type");
3364 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003365 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3366 NumArgs);
3367 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003368
Douglas Gregora8e02e72009-07-28 23:00:59 +00003369 // Allocate the (non-canonical) template specialization type, but don't
3370 // try to unique it: these types typically have location information that
3371 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003372 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3373 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003374 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003375 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003376 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003377 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3378 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003379
Douglas Gregor8bf42052009-02-09 18:46:07 +00003380 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003381 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003382}
3383
Mike Stump11289f42009-09-09 15:08:12 +00003384QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003385ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3386 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003387 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003388 assert(!Template.getAsDependentTemplateName() &&
3389 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003390
Douglas Gregore29139c2011-03-03 17:04:51 +00003391 // Look through qualified template names.
3392 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3393 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003394
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003395 // Build the canonical template specialization type.
3396 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003397 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003398 CanonArgs.reserve(NumArgs);
3399 for (unsigned I = 0; I != NumArgs; ++I)
3400 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3401
3402 // Determine whether this canonical template specialization type already
3403 // exists.
3404 llvm::FoldingSetNodeID ID;
3405 TemplateSpecializationType::Profile(ID, CanonTemplate,
3406 CanonArgs.data(), NumArgs, *this);
3407
Craig Topper36250ad2014-05-12 05:36:57 +00003408 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003409 TemplateSpecializationType *Spec
3410 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3411
3412 if (!Spec) {
3413 // Allocate a new canonical template specialization type.
3414 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3415 sizeof(TemplateArgument) * NumArgs),
3416 TypeAlignment);
3417 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3418 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003419 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003420 Types.push_back(Spec);
3421 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3422 }
3423
3424 assert(Spec->isDependentType() &&
3425 "Non-dependent template-id type must have a canonical type");
3426 return QualType(Spec, 0);
3427}
3428
3429QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003430ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3431 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003432 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003433 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003434 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003435
Craig Topper36250ad2014-05-12 05:36:57 +00003436 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003437 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003438 if (T)
3439 return QualType(T, 0);
3440
Douglas Gregorc42075a2010-02-04 18:10:26 +00003441 QualType Canon = NamedType;
3442 if (!Canon.isCanonical()) {
3443 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003444 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3445 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003446 (void)CheckT;
3447 }
3448
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003449 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003450 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003451 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003452 return QualType(T, 0);
3453}
3454
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003455QualType
Jay Foad39c79802011-01-12 09:06:06 +00003456ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003457 llvm::FoldingSetNodeID ID;
3458 ParenType::Profile(ID, InnerType);
3459
Craig Topper36250ad2014-05-12 05:36:57 +00003460 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003461 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3462 if (T)
3463 return QualType(T, 0);
3464
3465 QualType Canon = InnerType;
3466 if (!Canon.isCanonical()) {
3467 Canon = getCanonicalType(InnerType);
3468 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3469 assert(!CheckT && "Paren canonical type broken");
3470 (void)CheckT;
3471 }
3472
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003473 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003474 Types.push_back(T);
3475 ParenTypes.InsertNode(T, InsertPos);
3476 return QualType(T, 0);
3477}
3478
Douglas Gregor02085352010-03-31 20:19:30 +00003479QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3480 NestedNameSpecifier *NNS,
3481 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003482 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003483 if (Canon.isNull()) {
3484 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003485 ElaboratedTypeKeyword CanonKeyword = Keyword;
3486 if (Keyword == ETK_None)
3487 CanonKeyword = ETK_Typename;
3488
3489 if (CanonNNS != NNS || CanonKeyword != Keyword)
3490 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003491 }
3492
3493 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003494 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003495
Craig Topper36250ad2014-05-12 05:36:57 +00003496 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003497 DependentNameType *T
3498 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003499 if (T)
3500 return QualType(T, 0);
3501
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003502 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003503 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003504 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003505 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003506}
3507
Mike Stump11289f42009-09-09 15:08:12 +00003508QualType
John McCallc392f372010-06-11 00:33:02 +00003509ASTContext::getDependentTemplateSpecializationType(
3510 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003511 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003512 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003513 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003514 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003515 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003516 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3517 ArgCopy.push_back(Args[I].getArgument());
3518 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3519 ArgCopy.size(),
3520 ArgCopy.data());
3521}
3522
3523QualType
3524ASTContext::getDependentTemplateSpecializationType(
3525 ElaboratedTypeKeyword Keyword,
3526 NestedNameSpecifier *NNS,
3527 const IdentifierInfo *Name,
3528 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003529 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003530 assert((!NNS || NNS->isDependent()) &&
3531 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003532
Douglas Gregorc42075a2010-02-04 18:10:26 +00003533 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003534 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3535 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003536
Craig Topper36250ad2014-05-12 05:36:57 +00003537 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003538 DependentTemplateSpecializationType *T
3539 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003540 if (T)
3541 return QualType(T, 0);
3542
John McCallc392f372010-06-11 00:33:02 +00003543 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003544
John McCallc392f372010-06-11 00:33:02 +00003545 ElaboratedTypeKeyword CanonKeyword = Keyword;
3546 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3547
3548 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003549 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003550 for (unsigned I = 0; I != NumArgs; ++I) {
3551 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3552 if (!CanonArgs[I].structurallyEquals(Args[I]))
3553 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003554 }
3555
John McCallc392f372010-06-11 00:33:02 +00003556 QualType Canon;
3557 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3558 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3559 Name, NumArgs,
3560 CanonArgs.data());
3561
3562 // Find the insert position again.
3563 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3564 }
3565
3566 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3567 sizeof(TemplateArgument) * NumArgs),
3568 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003569 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003570 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003571 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003572 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003573 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003574}
3575
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003576QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003577 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003578 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003579 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003580
3581 assert(Pattern->containsUnexpandedParameterPack() &&
3582 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003583 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003584 PackExpansionType *T
3585 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3586 if (T)
3587 return QualType(T, 0);
3588
3589 QualType Canon;
3590 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003591 Canon = getCanonicalType(Pattern);
3592 // The canonical type might not contain an unexpanded parameter pack, if it
3593 // contains an alias template specialization which ignores one of its
3594 // parameters.
3595 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003596 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003597
Richard Smith68eea502012-07-16 00:20:35 +00003598 // Find the insert position again, in case we inserted an element into
3599 // PackExpansionTypes and invalidated our insert position.
3600 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3601 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003602 }
3603
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003604 T = new (*this, TypeAlignment)
3605 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003606 Types.push_back(T);
3607 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003608 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003609}
3610
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003611/// CmpProtocolNames - Comparison predicate for sorting protocols
3612/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003613static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3614 ObjCProtocolDecl *const *RHS) {
3615 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003616}
3617
John McCall8b07ec22010-05-15 11:32:37 +00003618static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003619 unsigned NumProtocols) {
3620 if (NumProtocols == 0) return true;
3621
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003622 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3623 return false;
3624
John McCallfc93cf92009-10-22 22:37:11 +00003625 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003626 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003627 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003628 return false;
3629 return true;
3630}
3631
3632static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003633 unsigned &NumProtocols) {
3634 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003635
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003636 // Sort protocols, keyed by name.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003637 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003638
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003639 // Canonicalize.
3640 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3641 Protocols[I] = Protocols[I]->getCanonicalDecl();
3642
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003643 // Remove duplicates.
3644 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3645 NumProtocols = ProtocolsEnd-Protocols;
3646}
3647
John McCall8b07ec22010-05-15 11:32:37 +00003648QualType ASTContext::getObjCObjectType(QualType BaseType,
3649 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003650 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003651 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003652 llvm::makeArrayRef(Protocols, NumProtocols),
3653 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003654}
3655
3656QualType ASTContext::getObjCObjectType(
3657 QualType baseType,
3658 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003659 ArrayRef<ObjCProtocolDecl *> protocols,
3660 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003661 // If the base type is an interface and there aren't any protocols or
3662 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003663 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3664 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003665 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003666
3667 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003668 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003669 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003670 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003671 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3672 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003673
Douglas Gregore9d95f12015-07-07 03:57:35 +00003674 // Determine the type arguments to be used for canonicalization,
3675 // which may be explicitly specified here or written on the base
3676 // type.
3677 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3678 if (effectiveTypeArgs.empty()) {
3679 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3680 effectiveTypeArgs = baseObject->getTypeArgs();
3681 }
John McCallfc93cf92009-10-22 22:37:11 +00003682
Douglas Gregore9d95f12015-07-07 03:57:35 +00003683 // Build the canonical type, which has the canonical base type and a
3684 // sorted-and-uniqued list of protocols and the type arguments
3685 // canonicalized.
3686 QualType canonical;
3687 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3688 effectiveTypeArgs.end(),
3689 [&](QualType type) {
3690 return type.isCanonical();
3691 });
3692 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3693 protocols.size());
3694 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3695 // Determine the canonical type arguments.
3696 ArrayRef<QualType> canonTypeArgs;
3697 SmallVector<QualType, 4> canonTypeArgsVec;
3698 if (!typeArgsAreCanonical) {
3699 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3700 for (auto typeArg : effectiveTypeArgs)
3701 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3702 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003703 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003704 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003705 }
3706
Douglas Gregore9d95f12015-07-07 03:57:35 +00003707 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3708 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3709 if (!protocolsSorted) {
3710 canonProtocolsVec.insert(canonProtocolsVec.begin(),
3711 protocols.begin(),
3712 protocols.end());
3713 unsigned uniqueCount = protocols.size();
3714 SortAndUniqueProtocols(&canonProtocolsVec[0], uniqueCount);
3715 canonProtocols = llvm::makeArrayRef(&canonProtocolsVec[0], uniqueCount);
3716 } else {
3717 canonProtocols = protocols;
3718 }
3719
3720 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003721 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003722
John McCallfc93cf92009-10-22 22:37:11 +00003723 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003724 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3725 }
3726
Douglas Gregore9d95f12015-07-07 03:57:35 +00003727 unsigned size = sizeof(ObjCObjectTypeImpl);
3728 size += typeArgs.size() * sizeof(QualType);
3729 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3730 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003731 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003732 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3733 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003734
3735 Types.push_back(T);
3736 ObjCObjectTypes.InsertNode(T, InsertPos);
3737 return QualType(T, 0);
3738}
3739
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003740/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3741/// protocol list adopt all protocols in QT's qualified-id protocol
3742/// list.
3743bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3744 ObjCInterfaceDecl *IC) {
3745 if (!QT->isObjCQualifiedIdType())
3746 return false;
3747
3748 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3749 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003750 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003751 if (!IC->ClassImplementsProtocol(Proto, false))
3752 return false;
3753 }
3754 return true;
3755 }
3756 return false;
3757}
3758
3759/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3760/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3761/// of protocols.
3762bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3763 ObjCInterfaceDecl *IDecl) {
3764 if (!QT->isObjCQualifiedIdType())
3765 return false;
3766 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3767 if (!OPT)
3768 return false;
3769 if (!IDecl->hasDefinition())
3770 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003771 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3772 CollectInheritedProtocols(IDecl, InheritedProtocols);
3773 if (InheritedProtocols.empty())
3774 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003775 // Check that if every protocol in list of id<plist> conforms to a protcol
3776 // of IDecl's, then bridge casting is ok.
3777 bool Conforms = false;
3778 for (auto *Proto : OPT->quals()) {
3779 Conforms = false;
3780 for (auto *PI : InheritedProtocols) {
3781 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3782 Conforms = true;
3783 break;
3784 }
3785 }
3786 if (!Conforms)
3787 break;
3788 }
3789 if (Conforms)
3790 return true;
3791
Aaron Ballman83731462014-03-17 16:14:00 +00003792 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003793 // If both the right and left sides have qualifiers.
3794 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003795 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003796 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003797 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003798 break;
3799 }
3800 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003801 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003802 }
3803 return true;
3804}
3805
John McCall8b07ec22010-05-15 11:32:37 +00003806/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3807/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003808QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003809 llvm::FoldingSetNodeID ID;
3810 ObjCObjectPointerType::Profile(ID, ObjectT);
3811
Craig Topper36250ad2014-05-12 05:36:57 +00003812 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003813 if (ObjCObjectPointerType *QT =
3814 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3815 return QualType(QT, 0);
3816
3817 // Find the canonical object type.
3818 QualType Canonical;
3819 if (!ObjectT.isCanonical()) {
3820 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3821
3822 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003823 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3824 }
3825
Douglas Gregorf85bee62010-02-08 22:59:26 +00003826 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003827 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3828 ObjCObjectPointerType *QType =
3829 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003830
Steve Narofffb4330f2009-06-17 22:40:22 +00003831 Types.push_back(QType);
3832 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003833 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003834}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003835
Douglas Gregor1c283312010-08-11 12:19:30 +00003836/// getObjCInterfaceType - Return the unique reference to the type for the
3837/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003838QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3839 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003840 if (Decl->TypeForDecl)
3841 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003842
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003843 if (PrevDecl) {
3844 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3845 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3846 return QualType(PrevDecl->TypeForDecl, 0);
3847 }
3848
Douglas Gregor7671e532011-12-16 16:34:57 +00003849 // Prefer the definition, if there is one.
3850 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3851 Decl = Def;
3852
Douglas Gregor1c283312010-08-11 12:19:30 +00003853 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3854 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3855 Decl->TypeForDecl = T;
3856 Types.push_back(T);
3857 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003858}
3859
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003860/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3861/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003862/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003863/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003864/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003865QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003866 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003867 if (tofExpr->isTypeDependent()) {
3868 llvm::FoldingSetNodeID ID;
3869 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003870
Craig Topper36250ad2014-05-12 05:36:57 +00003871 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003872 DependentTypeOfExprType *Canon
3873 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3874 if (Canon) {
3875 // We already have a "canonical" version of an identical, dependent
3876 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003877 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003878 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003879 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003880 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003881 Canon
3882 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003883 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3884 toe = Canon;
3885 }
3886 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003887 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003888 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003889 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003890 Types.push_back(toe);
3891 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003892}
3893
Steve Naroffa773cd52007-08-01 18:02:17 +00003894/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003895/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003896/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003897/// an issue. This doesn't affect the type checker, since it operates
3898/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003899QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003900 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003901 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003902 Types.push_back(tot);
3903 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003904}
3905
Anders Carlssonad6bd352009-06-24 21:24:56 +00003906
Richard Smith8eb1d322014-06-05 20:13:13 +00003907/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3908/// nodes. This would never be helpful, since each such type has its own
3909/// expression, and would not give a significant memory saving, since there
3910/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003911QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003912 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003913
3914 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003915 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003916 // unique dependent type. Two such decltype-specifiers refer to the same
3917 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003918 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003919 llvm::FoldingSetNodeID ID;
3920 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003921
Craig Topper36250ad2014-05-12 05:36:57 +00003922 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003923 DependentDecltypeType *Canon
3924 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003925 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003926 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003927 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003928 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003929 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003930 dt = new (*this, TypeAlignment)
3931 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003932 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003933 dt = new (*this, TypeAlignment)
3934 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003935 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003936 Types.push_back(dt);
3937 return QualType(dt, 0);
3938}
3939
Alexis Hunte852b102011-05-24 22:41:36 +00003940/// getUnaryTransformationType - We don't unique these, since the memory
3941/// savings are minimal and these are rare.
3942QualType ASTContext::getUnaryTransformType(QualType BaseType,
3943 QualType UnderlyingType,
3944 UnaryTransformType::UTTKind Kind)
3945 const {
3946 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003947 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3948 Kind,
3949 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003950 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003951 Types.push_back(Ty);
3952 return QualType(Ty, 0);
3953}
3954
Richard Smith2a7d4812013-05-04 07:00:32 +00003955/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3956/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3957/// canonical deduced-but-dependent 'auto' type.
3958QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003959 bool IsDependent) const {
3960 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003961 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003962
Richard Smith2a7d4812013-05-04 07:00:32 +00003963 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003964 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003965 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003966 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003967 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3968 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003969
Richard Smith74aeef52013-04-26 16:15:35 +00003970 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003971 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003972 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003973 Types.push_back(AT);
3974 if (InsertPos)
3975 AutoTypes.InsertNode(AT, InsertPos);
3976 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003977}
3978
Eli Friedman0dfb8892011-10-06 23:00:33 +00003979/// getAtomicType - Return the uniqued reference to the atomic type for
3980/// the given value type.
3981QualType ASTContext::getAtomicType(QualType T) const {
3982 // Unique pointers, to guarantee there is only one pointer of a particular
3983 // structure.
3984 llvm::FoldingSetNodeID ID;
3985 AtomicType::Profile(ID, T);
3986
Craig Topper36250ad2014-05-12 05:36:57 +00003987 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00003988 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3989 return QualType(AT, 0);
3990
3991 // If the atomic value type isn't canonical, this won't be a canonical type
3992 // either, so fill in the canonical type field.
3993 QualType Canonical;
3994 if (!T.isCanonical()) {
3995 Canonical = getAtomicType(getCanonicalType(T));
3996
3997 // Get the new insert position for the node we care about.
3998 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003999 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004000 }
4001 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4002 Types.push_back(New);
4003 AtomicTypes.InsertNode(New, InsertPos);
4004 return QualType(New, 0);
4005}
4006
Richard Smith02e85f32011-04-14 22:09:26 +00004007/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4008QualType ASTContext::getAutoDeductType() const {
4009 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004010 AutoDeductTy = QualType(
4011 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004012 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004013 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004014 return AutoDeductTy;
4015}
4016
4017/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4018QualType ASTContext::getAutoRRefDeductType() const {
4019 if (AutoRRefDeductTy.isNull())
4020 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4021 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4022 return AutoRRefDeductTy;
4023}
4024
Chris Lattnerfb072462007-01-23 05:45:31 +00004025/// getTagDeclType - Return the unique reference to the type for the
4026/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004027QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004028 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004029 // FIXME: What is the design on getTagDeclType when it requires casting
4030 // away const? mutable?
4031 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004032}
4033
Mike Stump11289f42009-09-09 15:08:12 +00004034/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4035/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4036/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004037CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004038 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004039}
Chris Lattnerfb072462007-01-23 05:45:31 +00004040
Hans Wennborg27541db2011-10-27 08:29:09 +00004041/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4042CanQualType ASTContext::getIntMaxType() const {
4043 return getFromTargetType(Target->getIntMaxType());
4044}
4045
4046/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4047CanQualType ASTContext::getUIntMaxType() const {
4048 return getFromTargetType(Target->getUIntMaxType());
4049}
4050
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004051/// getSignedWCharType - Return the type of "signed wchar_t".
4052/// Used when in C++, as a GCC extension.
4053QualType ASTContext::getSignedWCharType() const {
4054 // FIXME: derive from "Target" ?
4055 return WCharTy;
4056}
4057
4058/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4059/// Used when in C++, as a GCC extension.
4060QualType ASTContext::getUnsignedWCharType() const {
4061 // FIXME: derive from "Target" ?
4062 return UnsignedIntTy;
4063}
4064
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004065QualType ASTContext::getIntPtrType() const {
4066 return getFromTargetType(Target->getIntPtrType());
4067}
4068
4069QualType ASTContext::getUIntPtrType() const {
4070 return getCorrespondingUnsignedType(getIntPtrType());
4071}
4072
Hans Wennborg27541db2011-10-27 08:29:09 +00004073/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004074/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4075QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004076 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004077}
4078
Eli Friedman4e91899e2012-11-27 02:58:24 +00004079/// \brief Return the unique type for "pid_t" defined in
4080/// <sys/types.h>. We need this to compute the correct type for vfork().
4081QualType ASTContext::getProcessIDType() const {
4082 return getFromTargetType(Target->getProcessIDType());
4083}
4084
Chris Lattnera21ad802008-04-02 05:18:44 +00004085//===----------------------------------------------------------------------===//
4086// Type Operators
4087//===----------------------------------------------------------------------===//
4088
Jay Foad39c79802011-01-12 09:06:06 +00004089CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004090 // Push qualifiers into arrays, and then discard any remaining
4091 // qualifiers.
4092 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004093 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004094 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004095 QualType Result;
4096 if (isa<ArrayType>(Ty)) {
4097 Result = getArrayDecayedType(QualType(Ty,0));
4098 } else if (isa<FunctionType>(Ty)) {
4099 Result = getPointerType(QualType(Ty, 0));
4100 } else {
4101 Result = QualType(Ty, 0);
4102 }
4103
4104 return CanQualType::CreateUnsafe(Result);
4105}
4106
John McCall6c9dd522011-01-18 07:41:22 +00004107QualType ASTContext::getUnqualifiedArrayType(QualType type,
4108 Qualifiers &quals) {
4109 SplitQualType splitType = type.getSplitUnqualifiedType();
4110
4111 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4112 // the unqualified desugared type and then drops it on the floor.
4113 // We then have to strip that sugar back off with
4114 // getUnqualifiedDesugaredType(), which is silly.
4115 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004116 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004117
4118 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004119 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004120 quals = splitType.Quals;
4121 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004122 }
4123
John McCall6c9dd522011-01-18 07:41:22 +00004124 // Otherwise, recurse on the array's element type.
4125 QualType elementType = AT->getElementType();
4126 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4127
4128 // If that didn't change the element type, AT has no qualifiers, so we
4129 // can just use the results in splitType.
4130 if (elementType == unqualElementType) {
4131 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004132 quals = splitType.Quals;
4133 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004134 }
4135
4136 // Otherwise, add in the qualifiers from the outermost type, then
4137 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004138 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004139
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004140 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004141 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004142 CAT->getSizeModifier(), 0);
4143 }
4144
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004145 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004146 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004147 }
4148
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004149 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004150 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004151 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004152 VAT->getSizeModifier(),
4153 VAT->getIndexTypeCVRQualifiers(),
4154 VAT->getBracketsRange());
4155 }
4156
4157 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004158 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004159 DSAT->getSizeModifier(), 0,
4160 SourceRange());
4161}
4162
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004163/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4164/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4165/// they point to and return true. If T1 and T2 aren't pointer types
4166/// or pointer-to-member types, or if they are not similar at this
4167/// level, returns false and leaves T1 and T2 unchanged. Top-level
4168/// qualifiers on T1 and T2 are ignored. This function will typically
4169/// be called in a loop that successively "unwraps" pointer and
4170/// pointer-to-member types to compare them at each level.
4171bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4172 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4173 *T2PtrType = T2->getAs<PointerType>();
4174 if (T1PtrType && T2PtrType) {
4175 T1 = T1PtrType->getPointeeType();
4176 T2 = T2PtrType->getPointeeType();
4177 return true;
4178 }
4179
4180 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4181 *T2MPType = T2->getAs<MemberPointerType>();
4182 if (T1MPType && T2MPType &&
4183 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4184 QualType(T2MPType->getClass(), 0))) {
4185 T1 = T1MPType->getPointeeType();
4186 T2 = T2MPType->getPointeeType();
4187 return true;
4188 }
4189
David Blaikiebbafb8a2012-03-11 07:00:24 +00004190 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004191 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4192 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4193 if (T1OPType && T2OPType) {
4194 T1 = T1OPType->getPointeeType();
4195 T2 = T2OPType->getPointeeType();
4196 return true;
4197 }
4198 }
4199
4200 // FIXME: Block pointers, too?
4201
4202 return false;
4203}
4204
Jay Foad39c79802011-01-12 09:06:06 +00004205DeclarationNameInfo
4206ASTContext::getNameForTemplate(TemplateName Name,
4207 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004208 switch (Name.getKind()) {
4209 case TemplateName::QualifiedTemplate:
4210 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004211 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004212 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4213 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004214
John McCalld9dfe3a2011-06-30 08:33:18 +00004215 case TemplateName::OverloadedTemplate: {
4216 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4217 // DNInfo work in progress: CHECKME: what about DNLoc?
4218 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4219 }
4220
4221 case TemplateName::DependentTemplate: {
4222 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004223 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004224 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004225 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4226 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004227 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004228 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4229 // DNInfo work in progress: FIXME: source locations?
4230 DeclarationNameLoc DNLoc;
4231 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4232 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4233 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004234 }
4235 }
4236
John McCalld9dfe3a2011-06-30 08:33:18 +00004237 case TemplateName::SubstTemplateTemplateParm: {
4238 SubstTemplateTemplateParmStorage *subst
4239 = Name.getAsSubstTemplateTemplateParm();
4240 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4241 NameLoc);
4242 }
4243
4244 case TemplateName::SubstTemplateTemplateParmPack: {
4245 SubstTemplateTemplateParmPackStorage *subst
4246 = Name.getAsSubstTemplateTemplateParmPack();
4247 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4248 NameLoc);
4249 }
4250 }
4251
4252 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004253}
4254
Jay Foad39c79802011-01-12 09:06:06 +00004255TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004256 switch (Name.getKind()) {
4257 case TemplateName::QualifiedTemplate:
4258 case TemplateName::Template: {
4259 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004260 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004261 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004262 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4263
4264 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004265 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004266 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004267
John McCalld9dfe3a2011-06-30 08:33:18 +00004268 case TemplateName::OverloadedTemplate:
4269 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004270
John McCalld9dfe3a2011-06-30 08:33:18 +00004271 case TemplateName::DependentTemplate: {
4272 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4273 assert(DTN && "Non-dependent template names must refer to template decls.");
4274 return DTN->CanonicalTemplateName;
4275 }
4276
4277 case TemplateName::SubstTemplateTemplateParm: {
4278 SubstTemplateTemplateParmStorage *subst
4279 = Name.getAsSubstTemplateTemplateParm();
4280 return getCanonicalTemplateName(subst->getReplacement());
4281 }
4282
4283 case TemplateName::SubstTemplateTemplateParmPack: {
4284 SubstTemplateTemplateParmPackStorage *subst
4285 = Name.getAsSubstTemplateTemplateParmPack();
4286 TemplateTemplateParmDecl *canonParameter
4287 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4288 TemplateArgument canonArgPack
4289 = getCanonicalTemplateArgument(subst->getArgumentPack());
4290 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4291 }
4292 }
4293
4294 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004295}
4296
Douglas Gregoradee3e32009-11-11 23:06:43 +00004297bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4298 X = getCanonicalTemplateName(X);
4299 Y = getCanonicalTemplateName(Y);
4300 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4301}
4302
Mike Stump11289f42009-09-09 15:08:12 +00004303TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004304ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004305 switch (Arg.getKind()) {
4306 case TemplateArgument::Null:
4307 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004308
Douglas Gregora8e02e72009-07-28 23:00:59 +00004309 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004310 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004311
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004312 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004313 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004314 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004315 }
Mike Stump11289f42009-09-09 15:08:12 +00004316
Eli Friedmanb826a002012-09-26 02:36:12 +00004317 case TemplateArgument::NullPtr:
4318 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4319 /*isNullPtr*/true);
4320
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004321 case TemplateArgument::Template:
4322 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004323
4324 case TemplateArgument::TemplateExpansion:
4325 return TemplateArgument(getCanonicalTemplateName(
4326 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004327 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004328
Douglas Gregora8e02e72009-07-28 23:00:59 +00004329 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004330 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004331
Douglas Gregora8e02e72009-07-28 23:00:59 +00004332 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004333 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004334
Douglas Gregora8e02e72009-07-28 23:00:59 +00004335 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004336 if (Arg.pack_size() == 0)
4337 return Arg;
4338
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004339 TemplateArgument *CanonArgs
4340 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004341 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004342 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004343 AEnd = Arg.pack_end();
4344 A != AEnd; (void)++A, ++Idx)
4345 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004346
Benjamin Kramercce63472015-08-05 09:40:22 +00004347 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004348 }
4349 }
4350
4351 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004352 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004353}
4354
Douglas Gregor333489b2009-03-27 23:10:48 +00004355NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004356ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004357 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004358 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004359
4360 switch (NNS->getKind()) {
4361 case NestedNameSpecifier::Identifier:
4362 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004363 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004364 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4365 NNS->getAsIdentifier());
4366
4367 case NestedNameSpecifier::Namespace:
4368 // A namespace is canonical; build a nested-name-specifier with
4369 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004370 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004371 NNS->getAsNamespace()->getOriginalNamespace());
4372
4373 case NestedNameSpecifier::NamespaceAlias:
4374 // A namespace is canonical; build a nested-name-specifier with
4375 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004376 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004377 NNS->getAsNamespaceAlias()->getNamespace()
4378 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004379
4380 case NestedNameSpecifier::TypeSpec:
4381 case NestedNameSpecifier::TypeSpecWithTemplate: {
4382 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004383
4384 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4385 // break it apart into its prefix and identifier, then reconsititute those
4386 // as the canonical nested-name-specifier. This is required to canonicalize
4387 // a dependent nested-name-specifier involving typedefs of dependent-name
4388 // types, e.g.,
4389 // typedef typename T::type T1;
4390 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004391 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4392 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004393 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004394
Eli Friedman5358a0a2012-03-03 04:09:56 +00004395 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4396 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4397 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004398 return NestedNameSpecifier::Create(*this, nullptr, false,
4399 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004400 }
4401
4402 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004403 case NestedNameSpecifier::Super:
4404 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004405 return NNS;
4406 }
4407
David Blaikie8a40f702012-01-17 06:56:22 +00004408 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004409}
4410
Chris Lattner7adf0762008-08-04 07:31:14 +00004411
Jay Foad39c79802011-01-12 09:06:06 +00004412const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004413 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004414 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004415 // Handle the common positive case fast.
4416 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4417 return AT;
4418 }
Mike Stump11289f42009-09-09 15:08:12 +00004419
John McCall8ccfcb52009-09-24 19:53:00 +00004420 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004421 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004422 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004423
John McCall8ccfcb52009-09-24 19:53:00 +00004424 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004425 // implements C99 6.7.3p8: "If the specification of an array type includes
4426 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004427
Chris Lattner7adf0762008-08-04 07:31:14 +00004428 // If we get here, we either have type qualifiers on the type, or we have
4429 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004430 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004431
John McCall33ddac02011-01-19 10:06:00 +00004432 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004433 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004434
Chris Lattner7adf0762008-08-04 07:31:14 +00004435 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004436 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004437 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004438 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004439
Chris Lattner7adf0762008-08-04 07:31:14 +00004440 // Otherwise, we have an array and we have qualifiers on it. Push the
4441 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004442 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004443
Chris Lattner7adf0762008-08-04 07:31:14 +00004444 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4445 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4446 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004447 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004448 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4449 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4450 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004451 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004452
Mike Stump11289f42009-09-09 15:08:12 +00004453 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004454 = dyn_cast<DependentSizedArrayType>(ATy))
4455 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004456 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004457 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004458 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004459 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004460 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004461
Chris Lattner7adf0762008-08-04 07:31:14 +00004462 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004463 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004464 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004465 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004466 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004467 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004468}
4469
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004470QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004471 if (T->isArrayType() || T->isFunctionType())
4472 return getDecayedType(T);
4473 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004474}
4475
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004476QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004477 T = getVariableArrayDecayedType(T);
4478 T = getAdjustedParameterType(T);
4479 return T.getUnqualifiedType();
4480}
4481
David Majnemerd09a51c2015-03-03 01:50:05 +00004482QualType ASTContext::getExceptionObjectType(QualType T) const {
4483 // C++ [except.throw]p3:
4484 // A throw-expression initializes a temporary object, called the exception
4485 // object, the type of which is determined by removing any top-level
4486 // cv-qualifiers from the static type of the operand of throw and adjusting
4487 // the type from "array of T" or "function returning T" to "pointer to T"
4488 // or "pointer to function returning T", [...]
4489 T = getVariableArrayDecayedType(T);
4490 if (T->isArrayType() || T->isFunctionType())
4491 T = getDecayedType(T);
4492 return T.getUnqualifiedType();
4493}
4494
Chris Lattnera21ad802008-04-02 05:18:44 +00004495/// getArrayDecayedType - Return the properly qualified result of decaying the
4496/// specified array type to a pointer. This operation is non-trivial when
4497/// handling typedefs etc. The canonical type of "T" must be an array type,
4498/// this returns a pointer to a properly qualified element of the array.
4499///
4500/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004501QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004502 // Get the element type with 'getAsArrayType' so that we don't lose any
4503 // typedefs in the element type of the array. This also handles propagation
4504 // of type qualifiers from the array type into the element type if present
4505 // (C99 6.7.3p8).
4506 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4507 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004508
Chris Lattner7adf0762008-08-04 07:31:14 +00004509 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004510
4511 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004512 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004513}
4514
John McCall33ddac02011-01-19 10:06:00 +00004515QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4516 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004517}
4518
John McCall33ddac02011-01-19 10:06:00 +00004519QualType ASTContext::getBaseElementType(QualType type) const {
4520 Qualifiers qs;
4521 while (true) {
4522 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004523 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004524 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004525
John McCall33ddac02011-01-19 10:06:00 +00004526 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004527 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004528 }
Mike Stump11289f42009-09-09 15:08:12 +00004529
John McCall33ddac02011-01-19 10:06:00 +00004530 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004531}
4532
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004533/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004534uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004535ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4536 uint64_t ElementCount = 1;
4537 do {
4538 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004539 CA = dyn_cast_or_null<ConstantArrayType>(
4540 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004541 } while (CA);
4542 return ElementCount;
4543}
4544
Steve Naroff0af91202007-04-27 21:51:21 +00004545/// getFloatingRank - Return a relative rank for floating point types.
4546/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004547static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004548 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004549 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004550
John McCall9dd450b2009-09-21 23:43:11 +00004551 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4552 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004553 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004554 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004555 case BuiltinType::Float: return FloatRank;
4556 case BuiltinType::Double: return DoubleRank;
4557 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004558 }
4559}
4560
Mike Stump11289f42009-09-09 15:08:12 +00004561/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4562/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004563/// 'typeDomain' is a real floating point or complex type.
4564/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004565QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4566 QualType Domain) const {
4567 FloatingRank EltRank = getFloatingRank(Size);
4568 if (Domain->isComplexType()) {
4569 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004570 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004571 case FloatRank: return FloatComplexTy;
4572 case DoubleRank: return DoubleComplexTy;
4573 case LongDoubleRank: return LongDoubleComplexTy;
4574 }
Steve Naroff0af91202007-04-27 21:51:21 +00004575 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004576
4577 assert(Domain->isRealFloatingType() && "Unknown domain!");
4578 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004579 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004580 case FloatRank: return FloatTy;
4581 case DoubleRank: return DoubleTy;
4582 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004583 }
David Blaikief47fa302012-01-17 02:30:50 +00004584 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004585}
4586
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004587/// getFloatingTypeOrder - Compare the rank of the two specified floating
4588/// point types, ignoring the domain of the type (i.e. 'double' ==
4589/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004590/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004591int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004592 FloatingRank LHSR = getFloatingRank(LHS);
4593 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004594
Chris Lattnerb90739d2008-04-06 23:38:49 +00004595 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004596 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004597 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004598 return 1;
4599 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004600}
4601
Chris Lattner76a00cf2008-04-06 22:59:24 +00004602/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4603/// routine will assert if passed a built-in type that isn't an integer or enum,
4604/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004605unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004606 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004607
Chris Lattner76a00cf2008-04-06 22:59:24 +00004608 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004609 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004610 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004611 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004612 case BuiltinType::Char_S:
4613 case BuiltinType::Char_U:
4614 case BuiltinType::SChar:
4615 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004616 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004617 case BuiltinType::Short:
4618 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004619 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004620 case BuiltinType::Int:
4621 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004622 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004623 case BuiltinType::Long:
4624 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004625 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004626 case BuiltinType::LongLong:
4627 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004628 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004629 case BuiltinType::Int128:
4630 case BuiltinType::UInt128:
4631 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004632 }
4633}
4634
Eli Friedman629ffb92009-08-20 04:21:42 +00004635/// \brief Whether this is a promotable bitfield reference according
4636/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4637///
4638/// \returns the type this bit-field will promote to, or NULL if no
4639/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004640QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004641 if (E->isTypeDependent() || E->isValueDependent())
4642 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004643
4644 // FIXME: We should not do this unless E->refersToBitField() is true. This
4645 // matters in C where getSourceBitField() will find bit-fields for various
4646 // cases where the source expression is not a bit-field designator.
4647
John McCalld25db7e2013-05-06 21:39:12 +00004648 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004649 if (!Field)
4650 return QualType();
4651
4652 QualType FT = Field->getType();
4653
Richard Smithcaf33902011-10-10 18:28:20 +00004654 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004655 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004656 // C++ [conv.prom]p5:
4657 // A prvalue for an integral bit-field can be converted to a prvalue of type
4658 // int if int can represent all the values of the bit-field; otherwise, it
4659 // can be converted to unsigned int if unsigned int can represent all the
4660 // values of the bit-field. If the bit-field is larger yet, no integral
4661 // promotion applies to it.
4662 // C11 6.3.1.1/2:
4663 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4664 // If an int can represent all values of the original type (as restricted by
4665 // the width, for a bit-field), the value is converted to an int; otherwise,
4666 // it is converted to an unsigned int.
4667 //
4668 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4669 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004670 if (BitWidth < IntSize)
4671 return IntTy;
4672
4673 if (BitWidth == IntSize)
4674 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4675
4676 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004677 // like the base type. GCC has some weird bugs in this area that we
4678 // deliberately do not follow (GCC follows a pre-standard resolution to
4679 // C's DR315 which treats bit-width as being part of the type, and this leaks
4680 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004681 return QualType();
4682}
4683
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004684/// getPromotedIntegerType - Returns the type that Promotable will
4685/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4686/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004687QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004688 assert(!Promotable.isNull());
4689 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004690 if (const EnumType *ET = Promotable->getAs<EnumType>())
4691 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004692
4693 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4694 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4695 // (3.9.1) can be converted to a prvalue of the first of the following
4696 // types that can represent all the values of its underlying type:
4697 // int, unsigned int, long int, unsigned long int, long long int, or
4698 // unsigned long long int [...]
4699 // FIXME: Is there some better way to compute this?
4700 if (BT->getKind() == BuiltinType::WChar_S ||
4701 BT->getKind() == BuiltinType::WChar_U ||
4702 BT->getKind() == BuiltinType::Char16 ||
4703 BT->getKind() == BuiltinType::Char32) {
4704 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4705 uint64_t FromSize = getTypeSize(BT);
4706 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4707 LongLongTy, UnsignedLongLongTy };
4708 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4709 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4710 if (FromSize < ToSize ||
4711 (FromSize == ToSize &&
4712 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4713 return PromoteTypes[Idx];
4714 }
4715 llvm_unreachable("char type should fit into long long");
4716 }
4717 }
4718
4719 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004720 if (Promotable->isSignedIntegerType())
4721 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004722 uint64_t PromotableSize = getIntWidth(Promotable);
4723 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004724 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4725 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4726}
4727
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004728/// \brief Recurses in pointer/array types until it finds an objc retainable
4729/// type and returns its ownership.
4730Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4731 while (!T.isNull()) {
4732 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4733 return T.getObjCLifetime();
4734 if (T->isArrayType())
4735 T = getBaseElementType(T);
4736 else if (const PointerType *PT = T->getAs<PointerType>())
4737 T = PT->getPointeeType();
4738 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004739 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004740 else
4741 break;
4742 }
4743
4744 return Qualifiers::OCL_None;
4745}
4746
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004747static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4748 // Incomplete enum types are not treated as integer types.
4749 // FIXME: In C++, enum types are never integer types.
4750 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4751 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004752 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004753}
4754
Mike Stump11289f42009-09-09 15:08:12 +00004755/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004756/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004757/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004758int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004759 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4760 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004761
4762 // Unwrap enums to their underlying type.
4763 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4764 LHSC = getIntegerTypeForEnum(ET);
4765 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4766 RHSC = getIntegerTypeForEnum(ET);
4767
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004768 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004769
Chris Lattner76a00cf2008-04-06 22:59:24 +00004770 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4771 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004772
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004773 unsigned LHSRank = getIntegerRank(LHSC);
4774 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004775
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004776 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4777 if (LHSRank == RHSRank) return 0;
4778 return LHSRank > RHSRank ? 1 : -1;
4779 }
Mike Stump11289f42009-09-09 15:08:12 +00004780
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004781 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4782 if (LHSUnsigned) {
4783 // If the unsigned [LHS] type is larger, return it.
4784 if (LHSRank >= RHSRank)
4785 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004786
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004787 // If the signed type can represent all values of the unsigned type, it
4788 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004789 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004790 return -1;
4791 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004792
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004793 // If the unsigned [RHS] type is larger, return it.
4794 if (RHSRank >= LHSRank)
4795 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004796
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004797 // If the signed type can represent all values of the unsigned type, it
4798 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004799 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004800 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004801}
Anders Carlsson98f07902007-08-17 05:31:46 +00004802
Mike Stump11289f42009-09-09 15:08:12 +00004803// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004804QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004805 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004806 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004807 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004808
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004809 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004810
Anders Carlsson98f07902007-08-17 05:31:46 +00004811 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004812 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004813 // int flags;
4814 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004815 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004816 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004817 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004818 FieldTypes[3] = LongTy;
4819
Anders Carlsson98f07902007-08-17 05:31:46 +00004820 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004821 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004822 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004823 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004824 SourceLocation(), nullptr,
4825 FieldTypes[i], /*TInfo=*/nullptr,
4826 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004827 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004828 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004829 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004830 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004831 }
4832
Douglas Gregord5058122010-02-11 01:19:42 +00004833 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004834 }
Mike Stump11289f42009-09-09 15:08:12 +00004835
Anders Carlsson98f07902007-08-17 05:31:46 +00004836 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004837}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004838
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004839QualType ASTContext::getObjCSuperType() const {
4840 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004841 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004842 TUDecl->addDecl(ObjCSuperTypeDecl);
4843 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4844 }
4845 return ObjCSuperType;
4846}
4847
Douglas Gregor512b0772009-04-23 22:29:11 +00004848void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004849 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004850 assert(Rec && "Invalid CFConstantStringType");
4851 CFConstantStringTypeDecl = Rec->getDecl();
4852}
4853
Jay Foad39c79802011-01-12 09:06:06 +00004854QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004855 if (BlockDescriptorType)
4856 return getTagDeclType(BlockDescriptorType);
4857
Alp Toker2dea15b2013-12-17 01:22:38 +00004858 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004859 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004860 RD = buildImplicitRecord("__block_descriptor");
4861 RD->startDefinition();
4862
Mike Stumpd0153282009-10-20 02:12:22 +00004863 QualType FieldTypes[] = {
4864 UnsignedLongTy,
4865 UnsignedLongTy,
4866 };
4867
Craig Topperd6d31ac2013-07-15 08:24:27 +00004868 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004869 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004870 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004871 };
4872
4873 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004874 FieldDecl *Field = FieldDecl::Create(
4875 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004876 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4877 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004878 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004879 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004880 }
4881
Alp Toker2dea15b2013-12-17 01:22:38 +00004882 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004883
Alp Toker2dea15b2013-12-17 01:22:38 +00004884 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004885
4886 return getTagDeclType(BlockDescriptorType);
4887}
4888
Jay Foad39c79802011-01-12 09:06:06 +00004889QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004890 if (BlockDescriptorExtendedType)
4891 return getTagDeclType(BlockDescriptorExtendedType);
4892
Alp Toker2dea15b2013-12-17 01:22:38 +00004893 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004894 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004895 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4896 RD->startDefinition();
4897
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004898 QualType FieldTypes[] = {
4899 UnsignedLongTy,
4900 UnsignedLongTy,
4901 getPointerType(VoidPtrTy),
4902 getPointerType(VoidPtrTy)
4903 };
4904
Craig Topperd6d31ac2013-07-15 08:24:27 +00004905 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004906 "reserved",
4907 "Size",
4908 "CopyFuncPtr",
4909 "DestroyFuncPtr"
4910 };
4911
4912 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004913 FieldDecl *Field = FieldDecl::Create(
4914 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004915 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4916 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004917 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004918 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004919 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004920 }
4921
Alp Toker2dea15b2013-12-17 01:22:38 +00004922 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004923
Alp Toker2dea15b2013-12-17 01:22:38 +00004924 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004925 return getTagDeclType(BlockDescriptorExtendedType);
4926}
4927
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004928/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4929/// requires copy/dispose. Note that this must match the logic
4930/// in buildByrefHelpers.
4931bool ASTContext::BlockRequiresCopying(QualType Ty,
4932 const VarDecl *D) {
4933 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4934 const Expr *copyExpr = getBlockVarCopyInits(D);
4935 if (!copyExpr && record->hasTrivialDestructor()) return false;
4936
Mike Stump94967902009-10-21 18:16:27 +00004937 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004938 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004939
4940 if (!Ty->isObjCRetainableType()) return false;
4941
4942 Qualifiers qs = Ty.getQualifiers();
4943
4944 // If we have lifetime, that dominates.
4945 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4946 assert(getLangOpts().ObjCAutoRefCount);
4947
4948 switch (lifetime) {
4949 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4950
4951 // These are just bits as far as the runtime is concerned.
4952 case Qualifiers::OCL_ExplicitNone:
4953 case Qualifiers::OCL_Autoreleasing:
4954 return false;
4955
4956 // Tell the runtime that this is ARC __weak, called by the
4957 // byref routines.
4958 case Qualifiers::OCL_Weak:
4959 // ARC __strong __block variables need to be retained.
4960 case Qualifiers::OCL_Strong:
4961 return true;
4962 }
4963 llvm_unreachable("fell out of lifetime switch!");
4964 }
4965 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4966 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004967}
4968
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004969bool ASTContext::getByrefLifetime(QualType Ty,
4970 Qualifiers::ObjCLifetime &LifeTime,
4971 bool &HasByrefExtendedLayout) const {
4972
4973 if (!getLangOpts().ObjC1 ||
4974 getLangOpts().getGC() != LangOptions::NonGC)
4975 return false;
4976
4977 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004978 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004979 HasByrefExtendedLayout = true;
4980 LifeTime = Qualifiers::OCL_None;
4981 }
4982 else if (getLangOpts().ObjCAutoRefCount)
4983 LifeTime = Ty.getObjCLifetime();
4984 // MRR.
4985 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4986 LifeTime = Qualifiers::OCL_ExplicitNone;
4987 else
4988 LifeTime = Qualifiers::OCL_None;
4989 return true;
4990}
4991
Douglas Gregorbab8a962011-09-08 01:46:34 +00004992TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4993 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004994 ObjCInstanceTypeDecl =
4995 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004996 return ObjCInstanceTypeDecl;
4997}
4998
Anders Carlsson18acd442007-10-29 06:33:42 +00004999// This returns true if a type has been typedefed to BOOL:
5000// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005001static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005002 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005003 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5004 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005005
Anders Carlssond8499822007-10-29 05:01:08 +00005006 return false;
5007}
5008
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005009/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005010/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005011CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005012 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5013 return CharUnits::Zero();
5014
Ken Dyck40775002010-01-11 17:06:35 +00005015 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005016
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005017 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005018 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005019 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005020 // Treat arrays as pointers, since that's how they're passed in.
5021 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005022 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005023 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005024}
5025
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005026bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5027 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
5028 VD->getType()->isIntegralOrEnumerationType() &&
Alexey Bataev15413ea2015-05-20 11:57:02 +00005029 VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005030}
5031
Ken Dyck40775002010-01-11 17:06:35 +00005032static inline
5033std::string charUnitsToString(const CharUnits &CU) {
5034 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005035}
5036
John McCall351762c2011-02-07 10:33:21 +00005037/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005038/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005039std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5040 std::string S;
5041
David Chisnall950a9512009-11-17 19:33:30 +00005042 const BlockDecl *Decl = Expr->getBlockDecl();
5043 QualType BlockTy =
5044 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5045 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005046 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005047 getObjCEncodingForMethodParameter(
5048 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5049 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005050 else
Alp Toker314cc812014-01-25 16:55:45 +00005051 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005052 // Compute size of all parameters.
5053 // Start with computing size of a pointer in number of bytes.
5054 // FIXME: There might(should) be a better way of doing this computation!
5055 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005056 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5057 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005058 for (auto PI : Decl->params()) {
5059 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005060 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005061 if (sz.isZero())
5062 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005063 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005064 ParmOffset += sz;
5065 }
5066 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005067 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005068 // Block pointer and offset.
5069 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005070
5071 // Argument types.
5072 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005073 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005074 QualType PType = PVDecl->getOriginalType();
5075 if (const ArrayType *AT =
5076 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5077 // Use array's original type only if it has known number of
5078 // elements.
5079 if (!isa<ConstantArrayType>(AT))
5080 PType = PVDecl->getType();
5081 } else if (PType->isFunctionType())
5082 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005083 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005084 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5085 S, true /*Extended*/);
5086 else
5087 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005088 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005089 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005090 }
John McCall351762c2011-02-07 10:33:21 +00005091
5092 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005093}
5094
Douglas Gregora9d84932011-05-27 01:19:52 +00005095bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005096 std::string& S) {
5097 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005098 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005099 CharUnits ParmOffset;
5100 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005101 for (auto PI : Decl->params()) {
5102 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005103 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005104 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005105 continue;
5106
David Chisnall50e4eba2010-12-30 14:05:53 +00005107 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005108 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005109 ParmOffset += sz;
5110 }
5111 S += charUnitsToString(ParmOffset);
5112 ParmOffset = CharUnits::Zero();
5113
5114 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005115 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005116 QualType PType = PVDecl->getOriginalType();
5117 if (const ArrayType *AT =
5118 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5119 // Use array's original type only if it has known number of
5120 // elements.
5121 if (!isa<ConstantArrayType>(AT))
5122 PType = PVDecl->getType();
5123 } else if (PType->isFunctionType())
5124 PType = PVDecl->getType();
5125 getObjCEncodingForType(PType, S);
5126 S += charUnitsToString(ParmOffset);
5127 ParmOffset += getObjCEncodingTypeSize(PType);
5128 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005129
5130 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005131}
5132
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005133/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5134/// method parameter or return type. If Extended, include class names and
5135/// block object types.
5136void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5137 QualType T, std::string& S,
5138 bool Extended) const {
5139 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5140 getObjCEncodingForTypeQualifier(QT, S);
5141 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005142 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005143 true /*OutermostType*/,
5144 false /*EncodingProperty*/,
5145 false /*StructField*/,
5146 Extended /*EncodeBlockParameters*/,
5147 Extended /*EncodeClassNames*/);
5148}
5149
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005150/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005151/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005152bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005153 std::string& S,
5154 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005155 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005156 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005157 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5158 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005159 // Compute size of all parameters.
5160 // Start with computing size of a pointer in number of bytes.
5161 // FIXME: There might(should) be a better way of doing this computation!
5162 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005163 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005164 // The first two arguments (self and _cmd) are pointers; account for
5165 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005166 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005167 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005168 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005169 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005170 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005171 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005172 continue;
5173
Ken Dyck40775002010-01-11 17:06:35 +00005174 assert (sz.isPositive() &&
5175 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005176 ParmOffset += sz;
5177 }
Ken Dyck40775002010-01-11 17:06:35 +00005178 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005179 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005180 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005181
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005182 // Argument types.
5183 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005184 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005185 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005186 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005187 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005188 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005189 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5190 // Use array's original type only if it has known number of
5191 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005192 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005193 PType = PVDecl->getType();
5194 } else if (PType->isFunctionType())
5195 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005196 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5197 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005198 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005199 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005200 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005201
5202 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005203}
5204
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005205ObjCPropertyImplDecl *
5206ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5207 const ObjCPropertyDecl *PD,
5208 const Decl *Container) const {
5209 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005210 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005211 if (const ObjCCategoryImplDecl *CID =
5212 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005213 for (auto *PID : CID->property_impls())
5214 if (PID->getPropertyDecl() == PD)
5215 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005216 } else {
5217 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5218 for (auto *PID : OID->property_impls())
5219 if (PID->getPropertyDecl() == PD)
5220 return PID;
5221 }
5222 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005223}
5224
Daniel Dunbar4932b362008-08-28 04:38:10 +00005225/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005226/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005227/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5228/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005229/// Property attributes are stored as a comma-delimited C string. The simple
5230/// attributes readonly and bycopy are encoded as single characters. The
5231/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5232/// encoded as single characters, followed by an identifier. Property types
5233/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005234/// these attributes are defined by the following enumeration:
5235/// @code
5236/// enum PropertyAttributes {
5237/// kPropertyReadOnly = 'R', // property is read-only.
5238/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5239/// kPropertyByref = '&', // property is a reference to the value last assigned
5240/// kPropertyDynamic = 'D', // property is dynamic
5241/// kPropertyGetter = 'G', // followed by getter selector name
5242/// kPropertySetter = 'S', // followed by setter selector name
5243/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005244/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005245/// kPropertyWeak = 'W' // 'weak' property
5246/// kPropertyStrong = 'P' // property GC'able
5247/// kPropertyNonAtomic = 'N' // property non-atomic
5248/// };
5249/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005250void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005251 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005252 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005253 // Collect information from the property implementation decl(s).
5254 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005255 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005256
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005257 if (ObjCPropertyImplDecl *PropertyImpDecl =
5258 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5259 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5260 Dynamic = true;
5261 else
5262 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005263 }
5264
5265 // FIXME: This is not very efficient.
5266 S = "T";
5267
5268 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005269 // GCC has some special rules regarding encoding of properties which
5270 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005271 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005272
5273 if (PD->isReadOnly()) {
5274 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005275 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5276 S += ",C";
5277 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5278 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005279 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5280 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005281 } else {
5282 switch (PD->getSetterKind()) {
5283 case ObjCPropertyDecl::Assign: break;
5284 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005285 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005286 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005287 }
5288 }
5289
5290 // It really isn't clear at all what this means, since properties
5291 // are "dynamic by default".
5292 if (Dynamic)
5293 S += ",D";
5294
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005295 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5296 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005297
Daniel Dunbar4932b362008-08-28 04:38:10 +00005298 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5299 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005300 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005301 }
5302
5303 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5304 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005305 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005306 }
5307
5308 if (SynthesizePID) {
5309 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5310 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005311 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005312 }
5313
5314 // FIXME: OBJCGC: weak & strong
5315}
5316
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005317/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005318/// Another legacy compatibility encoding: 32-bit longs are encoded as
5319/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005320/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5321///
5322void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005323 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005324 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005325 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005326 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005327 else
Jay Foad39c79802011-01-12 09:06:06 +00005328 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005329 PointeeTy = IntTy;
5330 }
5331 }
5332}
5333
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005334void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005335 const FieldDecl *Field,
5336 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005337 // We follow the behavior of gcc, expanding structures which are
5338 // directly pointed to, and expanding embedded structures. Note that
5339 // these rules are sufficient to prevent recursive encoding of the
5340 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005341 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005342 true /* outermost type */, false, false,
5343 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005344}
5345
Joe Groff98ac7d22014-07-07 22:25:15 +00005346void ASTContext::getObjCEncodingForPropertyType(QualType T,
5347 std::string& S) const {
5348 // Encode result type.
5349 // GCC has some special rules regarding encoding of properties which
5350 // closely resembles encoding of ivars.
5351 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5352 true /* outermost type */,
5353 true /* encoding property */);
5354}
5355
John McCall393a78d2012-12-20 02:45:14 +00005356static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5357 BuiltinType::Kind kind) {
5358 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005359 case BuiltinType::Void: return 'v';
5360 case BuiltinType::Bool: return 'B';
5361 case BuiltinType::Char_U:
5362 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005363 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005364 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005365 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005366 case BuiltinType::UInt: return 'I';
5367 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005368 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005369 case BuiltinType::UInt128: return 'T';
5370 case BuiltinType::ULongLong: return 'Q';
5371 case BuiltinType::Char_S:
5372 case BuiltinType::SChar: return 'c';
5373 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005374 case BuiltinType::WChar_S:
5375 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005376 case BuiltinType::Int: return 'i';
5377 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005378 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005379 case BuiltinType::LongLong: return 'q';
5380 case BuiltinType::Int128: return 't';
5381 case BuiltinType::Float: return 'f';
5382 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005383 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005384 case BuiltinType::NullPtr: return '*'; // like char*
5385
5386 case BuiltinType::Half:
5387 // FIXME: potentially need @encodes for these!
5388 return ' ';
5389
5390 case BuiltinType::ObjCId:
5391 case BuiltinType::ObjCClass:
5392 case BuiltinType::ObjCSel:
5393 llvm_unreachable("@encoding ObjC primitive type");
5394
5395 // OpenCL and placeholder types don't need @encodings.
5396 case BuiltinType::OCLImage1d:
5397 case BuiltinType::OCLImage1dArray:
5398 case BuiltinType::OCLImage1dBuffer:
5399 case BuiltinType::OCLImage2d:
5400 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005401 case BuiltinType::OCLImage2dDepth:
5402 case BuiltinType::OCLImage2dArrayDepth:
5403 case BuiltinType::OCLImage2dMSAA:
5404 case BuiltinType::OCLImage2dArrayMSAA:
5405 case BuiltinType::OCLImage2dMSAADepth:
5406 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005407 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005408 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005409 case BuiltinType::OCLClkEvent:
5410 case BuiltinType::OCLQueue:
5411 case BuiltinType::OCLNDRange:
5412 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005413 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005414 case BuiltinType::Dependent:
5415#define BUILTIN_TYPE(KIND, ID)
5416#define PLACEHOLDER_TYPE(KIND, ID) \
5417 case BuiltinType::KIND:
5418#include "clang/AST/BuiltinTypes.def"
5419 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005420 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005421 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005422}
5423
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005424static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5425 EnumDecl *Enum = ET->getDecl();
5426
5427 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5428 if (!Enum->isFixed())
5429 return 'i';
5430
5431 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005432 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5433 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005434}
5435
Jay Foad39c79802011-01-12 09:06:06 +00005436static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005437 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005438 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005439 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005440 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5441 // The GNU runtime requires more information; bitfields are encoded as b,
5442 // then the offset (in bits) of the first element, then the type of the
5443 // bitfield, then the size in bits. For example, in this structure:
5444 //
5445 // struct
5446 // {
5447 // int integer;
5448 // int flags:2;
5449 // };
5450 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5451 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5452 // information is not especially sensible, but we're stuck with it for
5453 // compatibility with GCC, although providing it breaks anything that
5454 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005455 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005456 const RecordDecl *RD = FD->getParent();
5457 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005458 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005459 if (const EnumType *ET = T->getAs<EnumType>())
5460 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005461 else {
5462 const BuiltinType *BT = T->castAs<BuiltinType>();
5463 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5464 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005465 }
Richard Smithcaf33902011-10-10 18:28:20 +00005466 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005467}
5468
Daniel Dunbar07d07852009-10-18 21:17:35 +00005469// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005470void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5471 bool ExpandPointedToStructures,
5472 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005473 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005474 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005475 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005476 bool StructField,
5477 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005478 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005479 bool EncodePointerToObjCTypedef,
5480 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005481 CanQualType CT = getCanonicalType(T);
5482 switch (CT->getTypeClass()) {
5483 case Type::Builtin:
5484 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005485 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005486 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005487 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5488 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5489 else
5490 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005491 return;
Mike Stump11289f42009-09-09 15:08:12 +00005492
John McCall393a78d2012-12-20 02:45:14 +00005493 case Type::Complex: {
5494 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005495 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005496 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005497 return;
5498 }
John McCall393a78d2012-12-20 02:45:14 +00005499
5500 case Type::Atomic: {
5501 const AtomicType *AT = T->castAs<AtomicType>();
5502 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005503 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005504 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005505 }
John McCall393a78d2012-12-20 02:45:14 +00005506
5507 // encoding for pointer or reference types.
5508 case Type::Pointer:
5509 case Type::LValueReference:
5510 case Type::RValueReference: {
5511 QualType PointeeTy;
5512 if (isa<PointerType>(CT)) {
5513 const PointerType *PT = T->castAs<PointerType>();
5514 if (PT->isObjCSelType()) {
5515 S += ':';
5516 return;
5517 }
5518 PointeeTy = PT->getPointeeType();
5519 } else {
5520 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5521 }
5522
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005523 bool isReadOnly = false;
5524 // For historical/compatibility reasons, the read-only qualifier of the
5525 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5526 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005527 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005528 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005529 if (OutermostType && T.isConstQualified()) {
5530 isReadOnly = true;
5531 S += 'r';
5532 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005533 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005534 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005535 while (P->getAs<PointerType>())
5536 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005537 if (P.isConstQualified()) {
5538 isReadOnly = true;
5539 S += 'r';
5540 }
5541 }
5542 if (isReadOnly) {
5543 // Another legacy compatibility encoding. Some ObjC qualifier and type
5544 // combinations need to be rearranged.
5545 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005546 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005547 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005548 }
Mike Stump11289f42009-09-09 15:08:12 +00005549
Anders Carlssond8499822007-10-29 05:01:08 +00005550 if (PointeeTy->isCharType()) {
5551 // char pointer types should be encoded as '*' unless it is a
5552 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005553 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005554 S += '*';
5555 return;
5556 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005557 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005558 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5559 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5560 S += '#';
5561 return;
5562 }
5563 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5564 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5565 S += '@';
5566 return;
5567 }
5568 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005569 }
Anders Carlssond8499822007-10-29 05:01:08 +00005570 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005571 getLegacyIntegralTypeEncoding(PointeeTy);
5572
Mike Stump11289f42009-09-09 15:08:12 +00005573 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005574 nullptr, false, false, false, false, false, false,
5575 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005576 return;
5577 }
John McCall393a78d2012-12-20 02:45:14 +00005578
5579 case Type::ConstantArray:
5580 case Type::IncompleteArray:
5581 case Type::VariableArray: {
5582 const ArrayType *AT = cast<ArrayType>(CT);
5583
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005584 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005585 // Incomplete arrays are encoded as a pointer to the array element.
5586 S += '^';
5587
Mike Stump11289f42009-09-09 15:08:12 +00005588 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005589 false, ExpandStructures, FD);
5590 } else {
5591 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005592
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005593 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5594 S += llvm::utostr(CAT->getSize().getZExtValue());
5595 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005596 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005597 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5598 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005599 S += '0';
5600 }
Mike Stump11289f42009-09-09 15:08:12 +00005601
5602 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005603 false, ExpandStructures, FD,
5604 false, false, false, false, false, false,
5605 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005606 S += ']';
5607 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005608 return;
5609 }
Mike Stump11289f42009-09-09 15:08:12 +00005610
John McCall393a78d2012-12-20 02:45:14 +00005611 case Type::FunctionNoProto:
5612 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005613 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005614 return;
Mike Stump11289f42009-09-09 15:08:12 +00005615
John McCall393a78d2012-12-20 02:45:14 +00005616 case Type::Record: {
5617 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005618 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005619 // Anonymous structures print as '?'
5620 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5621 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005622 if (ClassTemplateSpecializationDecl *Spec
5623 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5624 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005625 llvm::raw_string_ostream OS(S);
5626 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005627 TemplateArgs.data(),
5628 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005629 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005630 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005631 } else {
5632 S += '?';
5633 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005634 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005635 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005636 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005637 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005638 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005639 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005640 if (FD) {
5641 S += '"';
5642 S += Field->getNameAsString();
5643 S += '"';
5644 }
Mike Stump11289f42009-09-09 15:08:12 +00005645
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005646 // Special case bit-fields.
5647 if (Field->isBitField()) {
5648 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005649 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005650 } else {
5651 QualType qt = Field->getType();
5652 getLegacyIntegralTypeEncoding(qt);
5653 getObjCEncodingForTypeImpl(qt, S, false, true,
5654 FD, /*OutermostType*/false,
5655 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005656 /*StructField*/true,
5657 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005658 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005659 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005660 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005661 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005662 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005663 return;
5664 }
Mike Stump11289f42009-09-09 15:08:12 +00005665
John McCall393a78d2012-12-20 02:45:14 +00005666 case Type::BlockPointer: {
5667 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005668 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005669 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005670 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005671
5672 S += '<';
5673 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005674 getObjCEncodingForTypeImpl(
5675 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5676 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005677 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5678 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005679 // Block self
5680 S += "@?";
5681 // Block parameters
5682 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005683 for (const auto &I : FPT->param_types())
5684 getObjCEncodingForTypeImpl(
5685 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5686 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005687 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5688 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005689 }
5690 S += '>';
5691 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005692 return;
5693 }
Mike Stump11289f42009-09-09 15:08:12 +00005694
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005695 case Type::ObjCObject: {
5696 // hack to match legacy encoding of *id and *Class
5697 QualType Ty = getObjCObjectPointerType(CT);
5698 if (Ty->isObjCIdType()) {
5699 S += "{objc_object=}";
5700 return;
5701 }
5702 else if (Ty->isObjCClassType()) {
5703 S += "{objc_class=}";
5704 return;
5705 }
5706 }
5707
John McCall393a78d2012-12-20 02:45:14 +00005708 case Type::ObjCInterface: {
5709 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005710 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005711 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005712 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005713 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005714 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005715 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005716 DeepCollectObjCIvars(OI, true, Ivars);
5717 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005718 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005719 if (Field->isBitField())
5720 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005721 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005722 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5723 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005724 EncodePointerToObjCTypedef,
5725 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005726 }
5727 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005728 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005729 }
Mike Stump11289f42009-09-09 15:08:12 +00005730
John McCall393a78d2012-12-20 02:45:14 +00005731 case Type::ObjCObjectPointer: {
5732 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005733 if (OPT->isObjCIdType()) {
5734 S += '@';
5735 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005736 }
Mike Stump11289f42009-09-09 15:08:12 +00005737
Steve Narofff0c86112009-10-28 22:03:49 +00005738 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5739 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5740 // Since this is a binary compatibility issue, need to consult with runtime
5741 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005742 S += '#';
5743 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005744 }
Mike Stump11289f42009-09-09 15:08:12 +00005745
Chris Lattnere7cabb92009-07-13 00:10:46 +00005746 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005747 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005748 ExpandPointedToStructures,
5749 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005750 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005751 // Note that we do extended encoding of protocol qualifer list
5752 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005753 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005754 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005755 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005756 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005757 S += '>';
5758 }
5759 S += '"';
5760 }
5761 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005762 }
Mike Stump11289f42009-09-09 15:08:12 +00005763
Chris Lattnere7cabb92009-07-13 00:10:46 +00005764 QualType PointeeTy = OPT->getPointeeType();
5765 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005766 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5767 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005768 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005769 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005770 // {...};
5771 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005772 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005773 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005774 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5775 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5776 DeepCollectObjCIvars(OI, true, Ivars);
5777 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5778 if (cast<FieldDecl>(Ivars[i]) == FD) {
5779 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005780 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005781 S += '}';
5782 return;
5783 }
5784 }
5785 }
Mike Stump11289f42009-09-09 15:08:12 +00005786 getObjCEncodingForTypeImpl(PointeeTy, S,
5787 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005788 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005789 false, false, false, false, false,
5790 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005791 return;
5792 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005793
5794 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005795 if (OPT->getInterfaceDecl() &&
5796 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005797 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005798 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005799 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005800 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005801 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005802 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005803 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005804 S += '"';
5805 }
5806 return;
5807 }
Mike Stump11289f42009-09-09 15:08:12 +00005808
John McCalla9e6e8d2010-05-17 23:56:34 +00005809 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005810 // FIXME: we shoul do better than that. 'M' is available.
5811 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005812 // This matches gcc's encoding, even though technically it is insufficient.
5813 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005814 case Type::Vector:
5815 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005816 // Until we have a coherent encoding of these three types, issue warning.
5817 { if (NotEncodedT)
5818 *NotEncodedT = T;
5819 return;
5820 }
5821
5822 // We could see an undeduced auto type here during error recovery.
5823 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005824 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005825 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005826
Richard Smith27d807c2013-04-30 13:56:41 +00005827
John McCall393a78d2012-12-20 02:45:14 +00005828#define ABSTRACT_TYPE(KIND, BASE)
5829#define TYPE(KIND, BASE)
5830#define DEPENDENT_TYPE(KIND, BASE) \
5831 case Type::KIND:
5832#define NON_CANONICAL_TYPE(KIND, BASE) \
5833 case Type::KIND:
5834#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5835 case Type::KIND:
5836#include "clang/AST/TypeNodes.def"
5837 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005838 }
John McCall393a78d2012-12-20 02:45:14 +00005839 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005840}
5841
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005842void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5843 std::string &S,
5844 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005845 bool includeVBases,
5846 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005847 assert(RDecl && "Expected non-null RecordDecl");
5848 assert(!RDecl->isUnion() && "Should not be called for unions");
5849 if (!RDecl->getDefinition())
5850 return;
5851
5852 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5853 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5854 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5855
5856 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005857 for (const auto &BI : CXXRec->bases()) {
5858 if (!BI.isVirtual()) {
5859 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005860 if (base->isEmpty())
5861 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005862 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005863 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5864 std::make_pair(offs, base));
5865 }
5866 }
5867 }
5868
5869 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005870 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005871 uint64_t offs = layout.getFieldOffset(i);
5872 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005873 std::make_pair(offs, Field));
5874 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005875 }
5876
5877 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005878 for (const auto &BI : CXXRec->vbases()) {
5879 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005880 if (base->isEmpty())
5881 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005882 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005883 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5884 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005885 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5886 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005887 }
5888 }
5889
5890 CharUnits size;
5891 if (CXXRec) {
5892 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5893 } else {
5894 size = layout.getSize();
5895 }
5896
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005897#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005898 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005899#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005900 std::multimap<uint64_t, NamedDecl *>::iterator
5901 CurLayObj = FieldOrBaseOffsets.begin();
5902
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005903 if (CXXRec && CXXRec->isDynamicClass() &&
5904 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005905 if (FD) {
5906 S += "\"_vptr$";
5907 std::string recname = CXXRec->getNameAsString();
5908 if (recname.empty()) recname = "?";
5909 S += recname;
5910 S += '"';
5911 }
5912 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005913#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005914 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005915#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005916 }
5917
5918 if (!RDecl->hasFlexibleArrayMember()) {
5919 // Mark the end of the structure.
5920 uint64_t offs = toBits(size);
5921 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005922 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005923 }
5924
5925 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005926#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005927 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005928 if (CurOffs < CurLayObj->first) {
5929 uint64_t padding = CurLayObj->first - CurOffs;
5930 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5931 // packing/alignment of members is different that normal, in which case
5932 // the encoding will be out-of-sync with the real layout.
5933 // If the runtime switches to just consider the size of types without
5934 // taking into account alignment, we could make padding explicit in the
5935 // encoding (e.g. using arrays of chars). The encoding strings would be
5936 // longer then though.
5937 CurOffs += padding;
5938 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005939#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005940
5941 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005942 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005943 break; // reached end of structure.
5944
5945 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5946 // We expand the bases without their virtual bases since those are going
5947 // in the initial structure. Note that this differs from gcc which
5948 // expands virtual bases each time one is encountered in the hierarchy,
5949 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005950 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5951 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005952 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005953#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005954 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005955#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005956 } else {
5957 FieldDecl *field = cast<FieldDecl>(dcl);
5958 if (FD) {
5959 S += '"';
5960 S += field->getNameAsString();
5961 S += '"';
5962 }
5963
5964 if (field->isBitField()) {
5965 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005966#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005967 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005968#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005969 } else {
5970 QualType qt = field->getType();
5971 getLegacyIntegralTypeEncoding(qt);
5972 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5973 /*OutermostType*/false,
5974 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005975 /*StructField*/true,
5976 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005977#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005978 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005979#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005980 }
5981 }
5982 }
5983}
5984
Mike Stump11289f42009-09-09 15:08:12 +00005985void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005986 std::string& S) const {
5987 if (QT & Decl::OBJC_TQ_In)
5988 S += 'n';
5989 if (QT & Decl::OBJC_TQ_Inout)
5990 S += 'N';
5991 if (QT & Decl::OBJC_TQ_Out)
5992 S += 'o';
5993 if (QT & Decl::OBJC_TQ_Bycopy)
5994 S += 'O';
5995 if (QT & Decl::OBJC_TQ_Byref)
5996 S += 'R';
5997 if (QT & Decl::OBJC_TQ_Oneway)
5998 S += 'V';
5999}
6000
Douglas Gregor3ea72692011-08-12 05:46:01 +00006001TypedefDecl *ASTContext::getObjCIdDecl() const {
6002 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006003 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006004 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006005 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006006 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006007 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006008}
6009
Douglas Gregor52e02802011-08-12 06:17:30 +00006010TypedefDecl *ASTContext::getObjCSelDecl() const {
6011 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006012 QualType T = getPointerType(ObjCBuiltinSelTy);
6013 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006014 }
6015 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006016}
6017
Douglas Gregor0a586182011-08-12 05:59:41 +00006018TypedefDecl *ASTContext::getObjCClassDecl() const {
6019 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006020 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006021 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006022 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006023 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006024 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006025}
6026
Douglas Gregord53ae832012-01-17 18:09:05 +00006027ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6028 if (!ObjCProtocolClassDecl) {
6029 ObjCProtocolClassDecl
6030 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6031 SourceLocation(),
6032 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006033 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006034 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006035 SourceLocation(), true);
6036 }
6037
6038 return ObjCProtocolClassDecl;
6039}
6040
Meador Inge5d3fb222012-06-16 03:34:49 +00006041//===----------------------------------------------------------------------===//
6042// __builtin_va_list Construction Functions
6043//===----------------------------------------------------------------------===//
6044
Charles Davisc7d5c942015-09-17 20:55:33 +00006045static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6046 StringRef Name) {
6047 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006048 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006049 return Context->buildImplicitTypedef(T, Name);
6050}
6051
6052static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6053 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6054}
6055
6056static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6057 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006058}
6059
6060static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6061 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006062 QualType T = Context->getPointerType(Context->VoidTy);
6063 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006064}
6065
Tim Northover9bb857a2013-01-31 12:13:10 +00006066static TypedefDecl *
6067CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006068 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006069 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006070 if (Context->getLangOpts().CPlusPlus) {
6071 // namespace std { struct __va_list {
6072 NamespaceDecl *NS;
6073 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6074 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006075 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006076 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006077 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006078 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006079 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006080 }
6081
6082 VaListTagDecl->startDefinition();
6083
6084 const size_t NumFields = 5;
6085 QualType FieldTypes[NumFields];
6086 const char *FieldNames[NumFields];
6087
6088 // void *__stack;
6089 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6090 FieldNames[0] = "__stack";
6091
6092 // void *__gr_top;
6093 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6094 FieldNames[1] = "__gr_top";
6095
6096 // void *__vr_top;
6097 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6098 FieldNames[2] = "__vr_top";
6099
6100 // int __gr_offs;
6101 FieldTypes[3] = Context->IntTy;
6102 FieldNames[3] = "__gr_offs";
6103
6104 // int __vr_offs;
6105 FieldTypes[4] = Context->IntTy;
6106 FieldNames[4] = "__vr_offs";
6107
6108 // Create fields
6109 for (unsigned i = 0; i < NumFields; ++i) {
6110 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6111 VaListTagDecl,
6112 SourceLocation(),
6113 SourceLocation(),
6114 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006115 FieldTypes[i], /*TInfo=*/nullptr,
6116 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006117 /*Mutable=*/false,
6118 ICIS_NoInit);
6119 Field->setAccess(AS_public);
6120 VaListTagDecl->addDecl(Field);
6121 }
6122 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006123 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006124 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006125
6126 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006127 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006128}
6129
Meador Inge5d3fb222012-06-16 03:34:49 +00006130static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6131 // typedef struct __va_list_tag {
6132 RecordDecl *VaListTagDecl;
6133
Alp Toker2dea15b2013-12-17 01:22:38 +00006134 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006135 VaListTagDecl->startDefinition();
6136
6137 const size_t NumFields = 5;
6138 QualType FieldTypes[NumFields];
6139 const char *FieldNames[NumFields];
6140
6141 // unsigned char gpr;
6142 FieldTypes[0] = Context->UnsignedCharTy;
6143 FieldNames[0] = "gpr";
6144
6145 // unsigned char fpr;
6146 FieldTypes[1] = Context->UnsignedCharTy;
6147 FieldNames[1] = "fpr";
6148
6149 // unsigned short reserved;
6150 FieldTypes[2] = Context->UnsignedShortTy;
6151 FieldNames[2] = "reserved";
6152
6153 // void* overflow_arg_area;
6154 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6155 FieldNames[3] = "overflow_arg_area";
6156
6157 // void* reg_save_area;
6158 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6159 FieldNames[4] = "reg_save_area";
6160
6161 // Create fields
6162 for (unsigned i = 0; i < NumFields; ++i) {
6163 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6164 SourceLocation(),
6165 SourceLocation(),
6166 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006167 FieldTypes[i], /*TInfo=*/nullptr,
6168 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006169 /*Mutable=*/false,
6170 ICIS_NoInit);
6171 Field->setAccess(AS_public);
6172 VaListTagDecl->addDecl(Field);
6173 }
6174 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006175 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006176 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6177
6178 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006179 TypedefDecl *VaListTagTypedefDecl =
6180 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6181
Meador Inge5d3fb222012-06-16 03:34:49 +00006182 QualType VaListTagTypedefType =
6183 Context->getTypedefType(VaListTagTypedefDecl);
6184
6185 // typedef __va_list_tag __builtin_va_list[1];
6186 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6187 QualType VaListTagArrayType
6188 = Context->getConstantArrayType(VaListTagTypedefType,
6189 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006190 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006191}
6192
6193static TypedefDecl *
6194CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006195 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006196 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006197 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006198 VaListTagDecl->startDefinition();
6199
6200 const size_t NumFields = 4;
6201 QualType FieldTypes[NumFields];
6202 const char *FieldNames[NumFields];
6203
6204 // unsigned gp_offset;
6205 FieldTypes[0] = Context->UnsignedIntTy;
6206 FieldNames[0] = "gp_offset";
6207
6208 // unsigned fp_offset;
6209 FieldTypes[1] = Context->UnsignedIntTy;
6210 FieldNames[1] = "fp_offset";
6211
6212 // void* overflow_arg_area;
6213 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6214 FieldNames[2] = "overflow_arg_area";
6215
6216 // void* reg_save_area;
6217 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6218 FieldNames[3] = "reg_save_area";
6219
6220 // Create fields
6221 for (unsigned i = 0; i < NumFields; ++i) {
6222 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6223 VaListTagDecl,
6224 SourceLocation(),
6225 SourceLocation(),
6226 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006227 FieldTypes[i], /*TInfo=*/nullptr,
6228 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006229 /*Mutable=*/false,
6230 ICIS_NoInit);
6231 Field->setAccess(AS_public);
6232 VaListTagDecl->addDecl(Field);
6233 }
6234 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006235 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006236 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6237
Richard Smith9b88a4c2015-07-27 05:40:23 +00006238 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006239
Richard Smith9b88a4c2015-07-27 05:40:23 +00006240 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006241 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006242 QualType VaListTagArrayType =
6243 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006244 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006245}
6246
6247static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6248 // typedef int __builtin_va_list[4];
6249 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6250 QualType IntArrayType
6251 = Context->getConstantArrayType(Context->IntTy,
6252 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006253 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006254}
6255
Logan Chien57086ce2012-10-10 06:56:20 +00006256static TypedefDecl *
6257CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006258 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006259 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006260 if (Context->getLangOpts().CPlusPlus) {
6261 // namespace std { struct __va_list {
6262 NamespaceDecl *NS;
6263 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6264 Context->getTranslationUnitDecl(),
6265 /*Inline*/false, SourceLocation(),
6266 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006267 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006268 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006269 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006270 }
6271
6272 VaListDecl->startDefinition();
6273
6274 // void * __ap;
6275 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6276 VaListDecl,
6277 SourceLocation(),
6278 SourceLocation(),
6279 &Context->Idents.get("__ap"),
6280 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006281 /*TInfo=*/nullptr,
6282 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006283 /*Mutable=*/false,
6284 ICIS_NoInit);
6285 Field->setAccess(AS_public);
6286 VaListDecl->addDecl(Field);
6287
6288 // };
6289 VaListDecl->completeDefinition();
6290
6291 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006292 QualType T = Context->getRecordType(VaListDecl);
6293 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006294}
6295
Ulrich Weigand47445072013-05-06 16:26:41 +00006296static TypedefDecl *
6297CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006298 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006299 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006300 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006301 VaListTagDecl->startDefinition();
6302
6303 const size_t NumFields = 4;
6304 QualType FieldTypes[NumFields];
6305 const char *FieldNames[NumFields];
6306
6307 // long __gpr;
6308 FieldTypes[0] = Context->LongTy;
6309 FieldNames[0] = "__gpr";
6310
6311 // long __fpr;
6312 FieldTypes[1] = Context->LongTy;
6313 FieldNames[1] = "__fpr";
6314
6315 // void *__overflow_arg_area;
6316 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6317 FieldNames[2] = "__overflow_arg_area";
6318
6319 // void *__reg_save_area;
6320 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6321 FieldNames[3] = "__reg_save_area";
6322
6323 // Create fields
6324 for (unsigned i = 0; i < NumFields; ++i) {
6325 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6326 VaListTagDecl,
6327 SourceLocation(),
6328 SourceLocation(),
6329 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006330 FieldTypes[i], /*TInfo=*/nullptr,
6331 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006332 /*Mutable=*/false,
6333 ICIS_NoInit);
6334 Field->setAccess(AS_public);
6335 VaListTagDecl->addDecl(Field);
6336 }
6337 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006338 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006339 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006340
Richard Smith9b88a4c2015-07-27 05:40:23 +00006341 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006342
6343 // typedef __va_list_tag __builtin_va_list[1];
6344 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006345 QualType VaListTagArrayType =
6346 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006347
Alp Toker56b5cc92013-12-15 10:36:26 +00006348 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006349}
6350
Meador Inge5d3fb222012-06-16 03:34:49 +00006351static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6352 TargetInfo::BuiltinVaListKind Kind) {
6353 switch (Kind) {
6354 case TargetInfo::CharPtrBuiltinVaList:
6355 return CreateCharPtrBuiltinVaListDecl(Context);
6356 case TargetInfo::VoidPtrBuiltinVaList:
6357 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006358 case TargetInfo::AArch64ABIBuiltinVaList:
6359 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006360 case TargetInfo::PowerABIBuiltinVaList:
6361 return CreatePowerABIBuiltinVaListDecl(Context);
6362 case TargetInfo::X86_64ABIBuiltinVaList:
6363 return CreateX86_64ABIBuiltinVaListDecl(Context);
6364 case TargetInfo::PNaClABIBuiltinVaList:
6365 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006366 case TargetInfo::AAPCSABIBuiltinVaList:
6367 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006368 case TargetInfo::SystemZBuiltinVaList:
6369 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006370 }
6371
6372 llvm_unreachable("Unhandled __builtin_va_list type kind");
6373}
6374
6375TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006376 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006377 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006378 assert(BuiltinVaListDecl->isImplicit());
6379 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006380
6381 return BuiltinVaListDecl;
6382}
6383
Richard Smith9b88a4c2015-07-27 05:40:23 +00006384Decl *ASTContext::getVaListTagDecl() const {
6385 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006386 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006387 if (!VaListTagDecl)
6388 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006389
Richard Smith9b88a4c2015-07-27 05:40:23 +00006390 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006391}
6392
Charles Davisc7d5c942015-09-17 20:55:33 +00006393TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6394 if (!BuiltinMSVaListDecl)
6395 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6396
6397 return BuiltinMSVaListDecl;
6398}
6399
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006400void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006401 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006402 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006403
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006404 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006405}
6406
John McCalld28ae272009-12-02 08:04:21 +00006407/// \brief Retrieve the template name that corresponds to a non-empty
6408/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006409TemplateName
6410ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6411 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006412 unsigned size = End - Begin;
6413 assert(size > 1 && "set is not overloaded!");
6414
6415 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6416 size * sizeof(FunctionTemplateDecl*));
6417 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6418
6419 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006420 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006421 NamedDecl *D = *I;
6422 assert(isa<FunctionTemplateDecl>(D) ||
6423 (isa<UsingShadowDecl>(D) &&
6424 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6425 *Storage++ = D;
6426 }
6427
6428 return TemplateName(OT);
6429}
6430
Douglas Gregordc572a32009-03-30 22:58:21 +00006431/// \brief Retrieve the template name that represents a qualified
6432/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006433TemplateName
6434ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6435 bool TemplateKeyword,
6436 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006437 assert(NNS && "Missing nested-name-specifier in qualified template name");
6438
Douglas Gregorc42075a2010-02-04 18:10:26 +00006439 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006440 llvm::FoldingSetNodeID ID;
6441 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6442
Craig Topper36250ad2014-05-12 05:36:57 +00006443 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006444 QualifiedTemplateName *QTN =
6445 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6446 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006447 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6448 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006449 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6450 }
6451
6452 return TemplateName(QTN);
6453}
6454
6455/// \brief Retrieve the template name that represents a dependent
6456/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006457TemplateName
6458ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6459 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006460 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006461 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006462
6463 llvm::FoldingSetNodeID ID;
6464 DependentTemplateName::Profile(ID, NNS, Name);
6465
Craig Topper36250ad2014-05-12 05:36:57 +00006466 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006467 DependentTemplateName *QTN =
6468 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6469
6470 if (QTN)
6471 return TemplateName(QTN);
6472
6473 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6474 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006475 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6476 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006477 } else {
6478 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006479 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6480 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006481 DependentTemplateName *CheckQTN =
6482 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6483 assert(!CheckQTN && "Dependent type name canonicalization broken");
6484 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006485 }
6486
6487 DependentTemplateNames.InsertNode(QTN, InsertPos);
6488 return TemplateName(QTN);
6489}
6490
Douglas Gregor71395fa2009-11-04 00:56:37 +00006491/// \brief Retrieve the template name that represents a dependent
6492/// template name such as \c MetaFun::template operator+.
6493TemplateName
6494ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006495 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006496 assert((!NNS || NNS->isDependent()) &&
6497 "Nested name specifier must be dependent");
6498
6499 llvm::FoldingSetNodeID ID;
6500 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006501
6502 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006503 DependentTemplateName *QTN
6504 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006505
6506 if (QTN)
6507 return TemplateName(QTN);
6508
6509 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6510 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006511 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6512 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006513 } else {
6514 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006515 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6516 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006517
6518 DependentTemplateName *CheckQTN
6519 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6520 assert(!CheckQTN && "Dependent template name canonicalization broken");
6521 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006522 }
6523
6524 DependentTemplateNames.InsertNode(QTN, InsertPos);
6525 return TemplateName(QTN);
6526}
6527
Douglas Gregor5590be02011-01-15 06:45:20 +00006528TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006529ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6530 TemplateName replacement) const {
6531 llvm::FoldingSetNodeID ID;
6532 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006533
6534 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006535 SubstTemplateTemplateParmStorage *subst
6536 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6537
6538 if (!subst) {
6539 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6540 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6541 }
6542
6543 return TemplateName(subst);
6544}
6545
6546TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006547ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6548 const TemplateArgument &ArgPack) const {
6549 ASTContext &Self = const_cast<ASTContext &>(*this);
6550 llvm::FoldingSetNodeID ID;
6551 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006552
6553 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006554 SubstTemplateTemplateParmPackStorage *Subst
6555 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6556
6557 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006558 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006559 ArgPack.pack_size(),
6560 ArgPack.pack_begin());
6561 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6562 }
6563
6564 return TemplateName(Subst);
6565}
6566
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006567/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006568/// TargetInfo, produce the corresponding type. The unsigned @p Type
6569/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006570CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006571 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006572 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006573 case TargetInfo::SignedChar: return SignedCharTy;
6574 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006575 case TargetInfo::SignedShort: return ShortTy;
6576 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6577 case TargetInfo::SignedInt: return IntTy;
6578 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6579 case TargetInfo::SignedLong: return LongTy;
6580 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6581 case TargetInfo::SignedLongLong: return LongLongTy;
6582 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6583 }
6584
David Blaikie83d382b2011-09-23 05:06:16 +00006585 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006586}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006587
6588//===----------------------------------------------------------------------===//
6589// Type Predicates.
6590//===----------------------------------------------------------------------===//
6591
Fariborz Jahanian96207692009-02-18 21:49:28 +00006592/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6593/// garbage collection attribute.
6594///
John McCall553d45a2011-01-12 00:34:59 +00006595Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006596 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006597 return Qualifiers::GCNone;
6598
David Blaikiebbafb8a2012-03-11 07:00:24 +00006599 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006600 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6601
6602 // Default behaviour under objective-C's gc is for ObjC pointers
6603 // (or pointers to them) be treated as though they were declared
6604 // as __strong.
6605 if (GCAttrs == Qualifiers::GCNone) {
6606 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6607 return Qualifiers::Strong;
6608 else if (Ty->isPointerType())
6609 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6610 } else {
6611 // It's not valid to set GC attributes on anything that isn't a
6612 // pointer.
6613#ifndef NDEBUG
6614 QualType CT = Ty->getCanonicalTypeInternal();
6615 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6616 CT = AT->getElementType();
6617 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6618#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006619 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006620 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006621}
6622
Chris Lattner49af6a42008-04-07 06:51:04 +00006623//===----------------------------------------------------------------------===//
6624// Type Compatibility Testing
6625//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006626
Mike Stump11289f42009-09-09 15:08:12 +00006627/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006628/// compatible.
6629static bool areCompatVectorTypes(const VectorType *LHS,
6630 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006631 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006632 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006633 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006634}
6635
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006636bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6637 QualType SecondVec) {
6638 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6639 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6640
6641 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6642 return true;
6643
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006644 // Treat Neon vector types and most AltiVec vector types as if they are the
6645 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006646 const VectorType *First = FirstVec->getAs<VectorType>();
6647 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006648 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006649 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006650 First->getVectorKind() != VectorType::AltiVecPixel &&
6651 First->getVectorKind() != VectorType::AltiVecBool &&
6652 Second->getVectorKind() != VectorType::AltiVecPixel &&
6653 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006654 return true;
6655
6656 return false;
6657}
6658
Steve Naroff8e6aee52009-07-23 01:01:38 +00006659//===----------------------------------------------------------------------===//
6660// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6661//===----------------------------------------------------------------------===//
6662
6663/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6664/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006665bool
6666ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6667 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006668 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006669 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006670 for (auto *PI : rProto->protocols())
6671 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006672 return true;
6673 return false;
6674}
6675
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006676/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6677/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006678bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6679 QualType rhs) {
6680 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6681 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6682 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6683
Aaron Ballman83731462014-03-17 16:14:00 +00006684 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006685 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006686 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006687 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6688 match = true;
6689 break;
6690 }
6691 }
6692 if (!match)
6693 return false;
6694 }
6695 return true;
6696}
6697
Steve Naroff8e6aee52009-07-23 01:01:38 +00006698/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6699/// ObjCQualifiedIDType.
6700bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6701 bool compare) {
6702 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006703 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006704 lhs->isObjCIdType() || lhs->isObjCClassType())
6705 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006706 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006707 rhs->isObjCIdType() || rhs->isObjCClassType())
6708 return true;
6709
6710 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006711 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006712
Steve Naroff8e6aee52009-07-23 01:01:38 +00006713 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006714
Steve Naroff8e6aee52009-07-23 01:01:38 +00006715 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006716 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006717 // make sure we check the class hierarchy.
6718 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006719 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006720 // when comparing an id<P> on lhs with a static type on rhs,
6721 // see if static class implements all of id's protocols, directly or
6722 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006723 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006724 return false;
6725 }
6726 }
6727 // If there are no qualifiers and no interface, we have an 'id'.
6728 return true;
6729 }
Mike Stump11289f42009-09-09 15:08:12 +00006730 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006731 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006732 bool match = false;
6733
6734 // when comparing an id<P> on lhs with a static type on rhs,
6735 // see if static class implements all of id's protocols, directly or
6736 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006737 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006738 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6739 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6740 match = true;
6741 break;
6742 }
6743 }
Mike Stump11289f42009-09-09 15:08:12 +00006744 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006745 // make sure we check the class hierarchy.
6746 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006747 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006748 // when comparing an id<P> on lhs with a static type on rhs,
6749 // see if static class implements all of id's protocols, directly or
6750 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006751 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006752 match = true;
6753 break;
6754 }
6755 }
6756 }
6757 if (!match)
6758 return false;
6759 }
Mike Stump11289f42009-09-09 15:08:12 +00006760
Steve Naroff8e6aee52009-07-23 01:01:38 +00006761 return true;
6762 }
Mike Stump11289f42009-09-09 15:08:12 +00006763
Steve Naroff8e6aee52009-07-23 01:01:38 +00006764 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6765 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6766
Mike Stump11289f42009-09-09 15:08:12 +00006767 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006768 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006769 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006770 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006771 bool match = false;
6772
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006773 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006774 // see if static class implements all of id's protocols, directly or
6775 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006776 // First, lhs protocols in the qualifier list must be found, direct
6777 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006778 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006779 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6780 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6781 match = true;
6782 break;
6783 }
6784 }
6785 if (!match)
6786 return false;
6787 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006788
6789 // Static class's protocols, or its super class or category protocols
6790 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6791 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6792 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6793 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6794 // This is rather dubious but matches gcc's behavior. If lhs has
6795 // no type qualifier and its class has no static protocol(s)
6796 // assume that it is mismatch.
6797 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6798 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006799 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006800 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006801 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006802 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6803 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6804 match = true;
6805 break;
6806 }
6807 }
6808 if (!match)
6809 return false;
6810 }
6811 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006812 return true;
6813 }
6814 return false;
6815}
6816
Eli Friedman47f77112008-08-22 00:56:42 +00006817/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006818/// compatible for assignment from RHS to LHS. This handles validation of any
6819/// protocol qualifiers on the LHS or RHS.
6820///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006821bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6822 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006823 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6824 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6825
Steve Naroff1329fa02009-07-15 18:40:39 +00006826 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006827 if (LHS->isObjCUnqualifiedIdOrClass() ||
6828 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006829 return true;
6830
Douglas Gregorab209d82015-07-07 03:58:42 +00006831 // Function object that propagates a successful result or handles
6832 // __kindof types.
6833 auto finish = [&](bool succeeded) -> bool {
6834 if (succeeded)
6835 return true;
6836
6837 if (!RHS->isKindOfType())
6838 return false;
6839
6840 // Strip off __kindof and protocol qualifiers, then check whether
6841 // we can assign the other way.
6842 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6843 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6844 };
6845
6846 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6847 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6848 QualType(RHSOPT,0),
6849 false));
6850 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006851
Douglas Gregorab209d82015-07-07 03:58:42 +00006852 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6853 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6854 QualType(RHSOPT,0)));
6855 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006856
John McCall8b07ec22010-05-15 11:32:37 +00006857 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006858 if (LHS->getInterface() && RHS->getInterface()) {
6859 return finish(canAssignObjCInterfaces(LHS, RHS));
6860 }
Mike Stump11289f42009-09-09 15:08:12 +00006861
Steve Naroff8e6aee52009-07-23 01:01:38 +00006862 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006863}
6864
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006865/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006866/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006867/// arguments in block literals. When passed as arguments, passing 'A*' where
6868/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6869/// not OK. For the return type, the opposite is not OK.
6870bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6871 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006872 const ObjCObjectPointerType *RHSOPT,
6873 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006874
6875 // Function object that propagates a successful result or handles
6876 // __kindof types.
6877 auto finish = [&](bool succeeded) -> bool {
6878 if (succeeded)
6879 return true;
6880
6881 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6882 if (!Expected->isKindOfType())
6883 return false;
6884
6885 // Strip off __kindof and protocol qualifiers, then check whether
6886 // we can assign the other way.
6887 return canAssignObjCInterfacesInBlockPointer(
6888 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6889 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6890 BlockReturnType);
6891 };
6892
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006893 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006894 return true;
6895
6896 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006897 return finish(RHSOPT->isObjCBuiltinType() ||
6898 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006899 }
6900
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006901 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006902 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6903 QualType(RHSOPT,0),
6904 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006905
6906 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6907 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6908 if (LHS && RHS) { // We have 2 user-defined types.
6909 if (LHS != RHS) {
6910 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006911 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006912 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006913 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006914 }
6915 else
6916 return true;
6917 }
6918 return false;
6919}
6920
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006921/// Comparison routine for Objective-C protocols to be used with
6922/// llvm::array_pod_sort.
6923static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6924 ObjCProtocolDecl * const *rhs) {
6925 return (*lhs)->getName().compare((*rhs)->getName());
6926
6927}
6928
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006929/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006930/// of protocols inherited from two distinct objective-c pointer objects with
6931/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006932/// It is used to build composite qualifier list of the composite type of
6933/// the conditional expression involving two objective-c pointer objects.
6934static
6935void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006936 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006937 const ObjCObjectPointerType *LHSOPT,
6938 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006939 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006940
John McCall8b07ec22010-05-15 11:32:37 +00006941 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6942 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6943 assert(LHS->getInterface() && "LHS must have an interface base");
6944 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006945
6946 // Add all of the protocols for the LHS.
6947 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6948
6949 // Start with the protocol qualifiers.
6950 for (auto proto : LHS->quals()) {
6951 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006952 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006953
6954 // Also add the protocols associated with the LHS interface.
6955 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6956
6957 // Add all of the protocls for the RHS.
6958 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6959
6960 // Start with the protocol qualifiers.
6961 for (auto proto : RHS->quals()) {
6962 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006963 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006964
6965 // Also add the protocols associated with the RHS interface.
6966 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6967
6968 // Compute the intersection of the collected protocol sets.
6969 for (auto proto : LHSProtocolSet) {
6970 if (RHSProtocolSet.count(proto))
6971 IntersectionSet.push_back(proto);
6972 }
6973
6974 // Compute the set of protocols that is implied by either the common type or
6975 // the protocols within the intersection.
6976 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6977 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6978
6979 // Remove any implied protocols from the list of inherited protocols.
6980 if (!ImpliedProtocols.empty()) {
6981 IntersectionSet.erase(
6982 std::remove_if(IntersectionSet.begin(),
6983 IntersectionSet.end(),
6984 [&](ObjCProtocolDecl *proto) -> bool {
6985 return ImpliedProtocols.count(proto) > 0;
6986 }),
6987 IntersectionSet.end());
6988 }
6989
6990 // Sort the remaining protocols by name.
6991 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
6992 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006993}
6994
Douglas Gregor1ac1b632015-07-07 03:58:54 +00006995/// Determine whether the first type is a subtype of the second.
6996static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
6997 QualType rhs) {
6998 // Common case: two object pointers.
6999 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7000 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7001 if (lhsOPT && rhsOPT)
7002 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7003
7004 // Two block pointers.
7005 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7006 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7007 if (lhsBlock && rhsBlock)
7008 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7009
7010 // If either is an unqualified 'id' and the other is a block, it's
7011 // acceptable.
7012 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7013 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7014 return true;
7015
7016 return false;
7017}
7018
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007019// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007020static bool sameObjCTypeArgs(ASTContext &ctx,
7021 const ObjCInterfaceDecl *iface,
7022 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007023 ArrayRef<QualType> rhsArgs,
7024 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007025 if (lhsArgs.size() != rhsArgs.size())
7026 return false;
7027
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007028 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007029 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007030 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7031 continue;
7032
7033 switch (typeParams->begin()[i]->getVariance()) {
7034 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007035 if (!stripKindOf ||
7036 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7037 rhsArgs[i].stripObjCKindOfType(ctx))) {
7038 return false;
7039 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007040 break;
7041
7042 case ObjCTypeParamVariance::Covariant:
7043 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7044 return false;
7045 break;
7046
7047 case ObjCTypeParamVariance::Contravariant:
7048 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7049 return false;
7050 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007051 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007052 }
7053
7054 return true;
7055}
7056
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007057QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007058 const ObjCObjectPointerType *Lptr,
7059 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007060 const ObjCObjectType *LHS = Lptr->getObjectType();
7061 const ObjCObjectType *RHS = Rptr->getObjectType();
7062 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7063 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007064
7065 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007066 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007067
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007068 // Follow the left-hand side up the class hierarchy until we either hit a
7069 // root or find the RHS. Record the ancestors in case we don't find it.
7070 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7071 LHSAncestors;
7072 while (true) {
7073 // Record this ancestor. We'll need this if the common type isn't in the
7074 // path from the LHS to the root.
7075 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007076
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007077 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7078 // Get the type arguments.
7079 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7080 bool anyChanges = false;
7081 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7082 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007083 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7084 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007085 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007086 return QualType();
7087 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7088 // If only one has type arguments, the result will not have type
7089 // arguments.
7090 LHSTypeArgs = { };
7091 anyChanges = true;
7092 }
7093
7094 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007095 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007096 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7097 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007098 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007099 anyChanges = true;
7100
7101 // If anything in the LHS will have changed, build a new result type.
7102 if (anyChanges) {
7103 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007104 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7105 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007106 return getObjCObjectPointerType(Result);
7107 }
7108
7109 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007110 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007111
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007112 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007113 QualType LHSSuperType = LHS->getSuperClassType();
7114 if (LHSSuperType.isNull())
7115 break;
7116
7117 LHS = LHSSuperType->castAs<ObjCObjectType>();
7118 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007119
7120 // We didn't find anything by following the LHS to its root; now check
7121 // the RHS against the cached set of ancestors.
7122 while (true) {
7123 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7124 if (KnownLHS != LHSAncestors.end()) {
7125 LHS = KnownLHS->second;
7126
7127 // Get the type arguments.
7128 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7129 bool anyChanges = false;
7130 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7131 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007132 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7133 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007134 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007135 return QualType();
7136 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7137 // If only one has type arguments, the result will not have type
7138 // arguments.
7139 RHSTypeArgs = { };
7140 anyChanges = true;
7141 }
7142
7143 // Compute the intersection of protocols.
7144 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7145 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7146 Protocols);
7147 if (!Protocols.empty())
7148 anyChanges = true;
7149
7150 if (anyChanges) {
7151 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007152 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7153 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007154 return getObjCObjectPointerType(Result);
7155 }
7156
7157 return getObjCObjectPointerType(QualType(RHS, 0));
7158 }
7159
7160 // Find the superclass of the RHS.
7161 QualType RHSSuperType = RHS->getSuperClassType();
7162 if (RHSSuperType.isNull())
7163 break;
7164
7165 RHS = RHSSuperType->castAs<ObjCObjectType>();
7166 }
7167
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007168 return QualType();
7169}
7170
John McCall8b07ec22010-05-15 11:32:37 +00007171bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7172 const ObjCObjectType *RHS) {
7173 assert(LHS->getInterface() && "LHS is not an interface type");
7174 assert(RHS->getInterface() && "RHS is not an interface type");
7175
Chris Lattner49af6a42008-04-07 06:51:04 +00007176 // Verify that the base decls are compatible: the RHS must be a subclass of
7177 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007178 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7179 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7180 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007181 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007182
Douglas Gregore83b9562015-07-07 03:57:53 +00007183 // If the LHS has protocol qualifiers, determine whether all of them are
7184 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7185 // LHS).
7186 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007187 // OK if conversion of LHS to SuperClass results in narrowing of types
7188 // ; i.e., SuperClass may implement at least one of the protocols
7189 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7190 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7191 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7192 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7193 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7194 // qualifiers.
7195 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007196 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007197 // If there is no protocols associated with RHS, it is not a match.
7198 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007199 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007200
7201 for (const auto *LHSProto : LHS->quals()) {
7202 bool SuperImplementsProtocol = false;
7203 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7204 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7205 SuperImplementsProtocol = true;
7206 break;
7207 }
7208 if (!SuperImplementsProtocol)
7209 return false;
7210 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007211 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007212
7213 // If the LHS is specialized, we may need to check type arguments.
7214 if (LHS->isSpecialized()) {
7215 // Follow the superclass chain until we've matched the LHS class in the
7216 // hierarchy. This substitutes type arguments through.
7217 const ObjCObjectType *RHSSuper = RHS;
7218 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7219 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7220
7221 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007222 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007223 !sameObjCTypeArgs(*this, LHS->getInterface(),
7224 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007225 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007226 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007227 }
7228 }
7229
7230 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007231}
7232
Steve Naroffb7605152009-02-12 17:52:19 +00007233bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7234 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007235 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7236 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007237
Steve Naroff7cae42b2009-07-10 23:34:53 +00007238 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007239 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007240
7241 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7242 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007243}
7244
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007245bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7246 return canAssignObjCInterfaces(
7247 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7248 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7249}
7250
Mike Stump11289f42009-09-09 15:08:12 +00007251/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007252/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007253/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007254/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007255bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7256 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007257 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007258 return hasSameType(LHS, RHS);
7259
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007260 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007261}
7262
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007263bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007264 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007265}
7266
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007267bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7268 return !mergeTypes(LHS, RHS, true).isNull();
7269}
7270
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007271/// mergeTransparentUnionType - if T is a transparent union type and a member
7272/// of T is compatible with SubType, return the merged type, else return
7273/// QualType()
7274QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7275 bool OfBlockPointer,
7276 bool Unqualified) {
7277 if (const RecordType *UT = T->getAsUnionType()) {
7278 RecordDecl *UD = UT->getDecl();
7279 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007280 for (const auto *I : UD->fields()) {
7281 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007282 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7283 if (!MT.isNull())
7284 return MT;
7285 }
7286 }
7287 }
7288
7289 return QualType();
7290}
7291
Alp Toker9cacbab2014-01-20 20:26:09 +00007292/// mergeFunctionParameterTypes - merge two types which appear as function
7293/// parameter types
7294QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7295 bool OfBlockPointer,
7296 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007297 // GNU extension: two types are compatible if they appear as a function
7298 // argument, one of the types is a transparent union type and the other
7299 // type is compatible with a union member
7300 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7301 Unqualified);
7302 if (!lmerge.isNull())
7303 return lmerge;
7304
7305 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7306 Unqualified);
7307 if (!rmerge.isNull())
7308 return rmerge;
7309
7310 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7311}
7312
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007313QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007314 bool OfBlockPointer,
7315 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007316 const FunctionType *lbase = lhs->getAs<FunctionType>();
7317 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007318 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7319 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007320 bool allLTypes = true;
7321 bool allRTypes = true;
7322
7323 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007324 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007325 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007326 QualType RHS = rbase->getReturnType();
7327 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007328 bool UnqualifiedResult = Unqualified;
7329 if (!UnqualifiedResult)
7330 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007331 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007332 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007333 else
Alp Toker314cc812014-01-25 16:55:45 +00007334 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007335 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007336 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007337
7338 if (Unqualified)
7339 retType = retType.getUnqualifiedType();
7340
Alp Toker314cc812014-01-25 16:55:45 +00007341 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7342 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007343 if (Unqualified) {
7344 LRetType = LRetType.getUnqualifiedType();
7345 RRetType = RRetType.getUnqualifiedType();
7346 }
7347
7348 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007349 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007350 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007351 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007352
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007353 // FIXME: double check this
7354 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7355 // rbase->getRegParmAttr() != 0 &&
7356 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007357 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7358 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007359
Douglas Gregor8c940862010-01-18 17:14:39 +00007360 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007361 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007362 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007363
John McCall8c6b56f2010-12-15 01:06:38 +00007364 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007365 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7366 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007367 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7368 return QualType();
7369
John McCall31168b02011-06-15 23:02:42 +00007370 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7371 return QualType();
7372
John McCall8c6b56f2010-12-15 01:06:38 +00007373 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7374 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007375
Rafael Espindola8778c282012-11-29 16:09:03 +00007376 if (lbaseInfo.getNoReturn() != NoReturn)
7377 allLTypes = false;
7378 if (rbaseInfo.getNoReturn() != NoReturn)
7379 allRTypes = false;
7380
John McCall31168b02011-06-15 23:02:42 +00007381 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007382
Eli Friedman47f77112008-08-22 00:56:42 +00007383 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007384 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7385 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007386 // Compatible functions must have the same number of parameters
7387 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007388 return QualType();
7389
7390 // Variadic and non-variadic functions aren't compatible
7391 if (lproto->isVariadic() != rproto->isVariadic())
7392 return QualType();
7393
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007394 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7395 return QualType();
7396
Fariborz Jahanian97676972011-09-28 21:52:05 +00007397 if (LangOpts.ObjCAutoRefCount &&
7398 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7399 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007400
7401 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007402 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007403 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7404 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7405 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7406 QualType paramType = mergeFunctionParameterTypes(
7407 lParamType, rParamType, OfBlockPointer, Unqualified);
7408 if (paramType.isNull())
7409 return QualType();
7410
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007411 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007412 paramType = paramType.getUnqualifiedType();
7413
7414 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007415 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007416 lParamType = lParamType.getUnqualifiedType();
7417 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007418 }
Alp Toker601b22c2014-01-21 23:35:24 +00007419
7420 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007421 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007422 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007423 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007424 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007425
Eli Friedman47f77112008-08-22 00:56:42 +00007426 if (allLTypes) return lhs;
7427 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007428
7429 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7430 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007431 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007432 }
7433
7434 if (lproto) allRTypes = false;
7435 if (rproto) allLTypes = false;
7436
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007437 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007438 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007439 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007440 if (proto->isVariadic()) return QualType();
7441 // Check that the types are compatible with the types that
7442 // would result from default argument promotions (C99 6.7.5.3p15).
7443 // The only types actually affected are promotable integer
7444 // types and floats, which would be passed as a different
7445 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007446 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7447 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007448
Eli Friedman448ce402012-08-30 00:44:15 +00007449 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007450 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007451 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7452 paramTy = Enum->getDecl()->getIntegerType();
7453 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007454 return QualType();
7455 }
Alp Toker601b22c2014-01-21 23:35:24 +00007456
7457 if (paramTy->isPromotableIntegerType() ||
7458 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007459 return QualType();
7460 }
7461
7462 if (allLTypes) return lhs;
7463 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007464
7465 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7466 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007467 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007468 }
7469
7470 if (allLTypes) return lhs;
7471 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007472 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007473}
7474
John McCall433c2e62013-03-21 00:10:07 +00007475/// Given that we have an enum type and a non-enum type, try to merge them.
7476static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7477 QualType other, bool isBlockReturnType) {
7478 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7479 // a signed integer type, or an unsigned integer type.
7480 // Compatibility is based on the underlying type, not the promotion
7481 // type.
7482 QualType underlyingType = ET->getDecl()->getIntegerType();
7483 if (underlyingType.isNull()) return QualType();
7484 if (Context.hasSameType(underlyingType, other))
7485 return other;
7486
7487 // In block return types, we're more permissive and accept any
7488 // integral type of the same size.
7489 if (isBlockReturnType && other->isIntegerType() &&
7490 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7491 return other;
7492
7493 return QualType();
7494}
7495
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007496QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007497 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007498 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007499 // C++ [expr]: If an expression initially has the type "reference to T", the
7500 // type is adjusted to "T" prior to any further analysis, the expression
7501 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007502 // expression is an lvalue unless the reference is an rvalue reference and
7503 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007504 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7505 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007506
7507 if (Unqualified) {
7508 LHS = LHS.getUnqualifiedType();
7509 RHS = RHS.getUnqualifiedType();
7510 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007511
Eli Friedman47f77112008-08-22 00:56:42 +00007512 QualType LHSCan = getCanonicalType(LHS),
7513 RHSCan = getCanonicalType(RHS);
7514
7515 // If two types are identical, they are compatible.
7516 if (LHSCan == RHSCan)
7517 return LHS;
7518
John McCall8ccfcb52009-09-24 19:53:00 +00007519 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007520 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7521 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007522 if (LQuals != RQuals) {
7523 // If any of these qualifiers are different, we have a type
7524 // mismatch.
7525 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007526 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7527 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007528 return QualType();
7529
7530 // Exactly one GC qualifier difference is allowed: __strong is
7531 // okay if the other type has no GC qualifier but is an Objective
7532 // C object pointer (i.e. implicitly strong by default). We fix
7533 // this by pretending that the unqualified type was actually
7534 // qualified __strong.
7535 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7536 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7537 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7538
7539 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7540 return QualType();
7541
7542 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7543 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7544 }
7545 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7546 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7547 }
Eli Friedman47f77112008-08-22 00:56:42 +00007548 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007549 }
7550
7551 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007552
Eli Friedmandcca6332009-06-01 01:22:52 +00007553 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7554 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007555
Chris Lattnerfd652912008-01-14 05:45:46 +00007556 // We want to consider the two function types to be the same for these
7557 // comparisons, just force one to the other.
7558 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7559 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007560
7561 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007562 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7563 LHSClass = Type::ConstantArray;
7564 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7565 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007566
John McCall8b07ec22010-05-15 11:32:37 +00007567 // ObjCInterfaces are just specialized ObjCObjects.
7568 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7569 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7570
Nate Begemance4d7fc2008-04-18 23:10:10 +00007571 // Canonicalize ExtVector -> Vector.
7572 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7573 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007574
Chris Lattner95554662008-04-07 05:43:21 +00007575 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007576 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007577 // Note that we only have special rules for turning block enum
7578 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007579 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007580 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007581 }
John McCall9dd450b2009-09-21 23:43:11 +00007582 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007583 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007584 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007585 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007586 if (OfBlockPointer && !BlockReturnType) {
7587 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7588 return LHS;
7589 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7590 return RHS;
7591 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007592
Eli Friedman47f77112008-08-22 00:56:42 +00007593 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007594 }
Eli Friedman47f77112008-08-22 00:56:42 +00007595
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007596 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007597 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007598#define TYPE(Class, Base)
7599#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007600#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007601#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7602#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7603#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007604 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007605
Richard Smith27d807c2013-04-30 13:56:41 +00007606 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007607 case Type::LValueReference:
7608 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007609 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007610 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007611
John McCall8b07ec22010-05-15 11:32:37 +00007612 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007613 case Type::IncompleteArray:
7614 case Type::VariableArray:
7615 case Type::FunctionProto:
7616 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007617 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007618
Chris Lattnerfd652912008-01-14 05:45:46 +00007619 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007620 {
7621 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007622 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7623 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007624 if (Unqualified) {
7625 LHSPointee = LHSPointee.getUnqualifiedType();
7626 RHSPointee = RHSPointee.getUnqualifiedType();
7627 }
7628 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7629 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007630 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007631 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007632 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007633 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007634 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007635 return getPointerType(ResultType);
7636 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007637 case Type::BlockPointer:
7638 {
7639 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007640 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7641 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007642 if (Unqualified) {
7643 LHSPointee = LHSPointee.getUnqualifiedType();
7644 RHSPointee = RHSPointee.getUnqualifiedType();
7645 }
7646 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7647 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007648 if (ResultType.isNull()) return QualType();
7649 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7650 return LHS;
7651 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7652 return RHS;
7653 return getBlockPointerType(ResultType);
7654 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007655 case Type::Atomic:
7656 {
7657 // Merge two pointer types, while trying to preserve typedef info
7658 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7659 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7660 if (Unqualified) {
7661 LHSValue = LHSValue.getUnqualifiedType();
7662 RHSValue = RHSValue.getUnqualifiedType();
7663 }
7664 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7665 Unqualified);
7666 if (ResultType.isNull()) return QualType();
7667 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7668 return LHS;
7669 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7670 return RHS;
7671 return getAtomicType(ResultType);
7672 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007673 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007674 {
7675 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7676 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7677 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7678 return QualType();
7679
7680 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7681 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007682 if (Unqualified) {
7683 LHSElem = LHSElem.getUnqualifiedType();
7684 RHSElem = RHSElem.getUnqualifiedType();
7685 }
7686
7687 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007688 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007689 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7690 return LHS;
7691 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7692 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007693 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7694 ArrayType::ArraySizeModifier(), 0);
7695 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7696 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007697 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7698 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007699 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7700 return LHS;
7701 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7702 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007703 if (LVAT) {
7704 // FIXME: This isn't correct! But tricky to implement because
7705 // the array's size has to be the size of LHS, but the type
7706 // has to be different.
7707 return LHS;
7708 }
7709 if (RVAT) {
7710 // FIXME: This isn't correct! But tricky to implement because
7711 // the array's size has to be the size of RHS, but the type
7712 // has to be different.
7713 return RHS;
7714 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007715 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7716 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007717 return getIncompleteArrayType(ResultType,
7718 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007719 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007720 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007721 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007722 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007723 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007724 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007725 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007726 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007727 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007728 case Type::Complex:
7729 // Distinct complex types are incompatible.
7730 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007731 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007732 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007733 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7734 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007735 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007736 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007737 case Type::ObjCObject: {
7738 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007739 // FIXME: This should be type compatibility, e.g. whether
7740 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007741 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7742 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7743 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007744 return LHS;
7745
Eli Friedman47f77112008-08-22 00:56:42 +00007746 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007747 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007748 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007749 if (OfBlockPointer) {
7750 if (canAssignObjCInterfacesInBlockPointer(
7751 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007752 RHS->getAs<ObjCObjectPointerType>(),
7753 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007754 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007755 return QualType();
7756 }
John McCall9dd450b2009-09-21 23:43:11 +00007757 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7758 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007759 return LHS;
7760
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007761 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007762 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007763 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007764
David Blaikie8a40f702012-01-17 06:56:22 +00007765 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007766}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007767
Fariborz Jahanian97676972011-09-28 21:52:05 +00007768bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7769 const FunctionProtoType *FromFunctionType,
7770 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007771 if (FromFunctionType->hasAnyConsumedParams() !=
7772 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007773 return false;
7774 FunctionProtoType::ExtProtoInfo FromEPI =
7775 FromFunctionType->getExtProtoInfo();
7776 FunctionProtoType::ExtProtoInfo ToEPI =
7777 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007778 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007779 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7780 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007781 return false;
7782 }
7783 return true;
7784}
7785
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007786/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7787/// 'RHS' attributes and returns the merged version; including for function
7788/// return types.
7789QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7790 QualType LHSCan = getCanonicalType(LHS),
7791 RHSCan = getCanonicalType(RHS);
7792 // If two types are identical, they are compatible.
7793 if (LHSCan == RHSCan)
7794 return LHS;
7795 if (RHSCan->isFunctionType()) {
7796 if (!LHSCan->isFunctionType())
7797 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007798 QualType OldReturnType =
7799 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007800 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007801 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007802 QualType ResReturnType =
7803 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7804 if (ResReturnType.isNull())
7805 return QualType();
7806 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7807 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7808 // In either case, use OldReturnType to build the new function type.
7809 const FunctionType *F = LHS->getAs<FunctionType>();
7810 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007811 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7812 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007813 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007814 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007815 return ResultType;
7816 }
7817 }
7818 return QualType();
7819 }
7820
7821 // If the qualifiers are different, the types can still be merged.
7822 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7823 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7824 if (LQuals != RQuals) {
7825 // If any of these qualifiers are different, we have a type mismatch.
7826 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7827 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7828 return QualType();
7829
7830 // Exactly one GC qualifier difference is allowed: __strong is
7831 // okay if the other type has no GC qualifier but is an Objective
7832 // C object pointer (i.e. implicitly strong by default). We fix
7833 // this by pretending that the unqualified type was actually
7834 // qualified __strong.
7835 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7836 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7837 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7838
7839 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7840 return QualType();
7841
7842 if (GC_L == Qualifiers::Strong)
7843 return LHS;
7844 if (GC_R == Qualifiers::Strong)
7845 return RHS;
7846 return QualType();
7847 }
7848
7849 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7850 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7851 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7852 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7853 if (ResQT == LHSBaseQT)
7854 return LHS;
7855 if (ResQT == RHSBaseQT)
7856 return RHS;
7857 }
7858 return QualType();
7859}
7860
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007861//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007862// Integer Predicates
7863//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007864
Jay Foad39c79802011-01-12 09:06:06 +00007865unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007866 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007867 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007868 if (T->isBooleanType())
7869 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007870 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007871 return (unsigned)getTypeSize(T);
7872}
7873
Abramo Bagnara13640492012-09-09 10:21:24 +00007874QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007875 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007876
7877 // Turn <4 x signed int> -> <4 x unsigned int>
7878 if (const VectorType *VTy = T->getAs<VectorType>())
7879 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007880 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007881
7882 // For enums, we return the unsigned version of the base type.
7883 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007884 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007885
7886 const BuiltinType *BTy = T->getAs<BuiltinType>();
7887 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007888 switch (BTy->getKind()) {
7889 case BuiltinType::Char_S:
7890 case BuiltinType::SChar:
7891 return UnsignedCharTy;
7892 case BuiltinType::Short:
7893 return UnsignedShortTy;
7894 case BuiltinType::Int:
7895 return UnsignedIntTy;
7896 case BuiltinType::Long:
7897 return UnsignedLongTy;
7898 case BuiltinType::LongLong:
7899 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007900 case BuiltinType::Int128:
7901 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007902 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007903 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007904 }
7905}
7906
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007907ASTMutationListener::~ASTMutationListener() { }
7908
Richard Smith1fa5d642013-05-11 05:45:24 +00007909void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7910 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007911
7912//===----------------------------------------------------------------------===//
7913// Builtin Type Computation
7914//===----------------------------------------------------------------------===//
7915
7916/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007917/// pointer over the consumed characters. This returns the resultant type. If
7918/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7919/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7920/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007921///
7922/// RequiresICE is filled in on return to indicate whether the value is required
7923/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007924static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007925 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007926 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007927 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007928 // Modifiers.
7929 int HowLong = 0;
7930 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007931 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007932
Chris Lattnerdc226c22010-10-01 22:42:38 +00007933 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007934 bool Done = false;
7935 while (!Done) {
7936 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007937 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007938 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007939 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007940 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007941 case 'S':
7942 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7943 assert(!Signed && "Can't use 'S' modifier multiple times!");
7944 Signed = true;
7945 break;
7946 case 'U':
7947 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007948 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007949 Unsigned = true;
7950 break;
7951 case 'L':
7952 assert(HowLong <= 2 && "Can't have LLLL modifier");
7953 ++HowLong;
7954 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007955 case 'W':
7956 // This modifier represents int64 type.
7957 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7958 switch (Context.getTargetInfo().getInt64Type()) {
7959 default:
7960 llvm_unreachable("Unexpected integer type");
7961 case TargetInfo::SignedLong:
7962 HowLong = 1;
7963 break;
7964 case TargetInfo::SignedLongLong:
7965 HowLong = 2;
7966 break;
7967 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007968 }
7969 }
7970
7971 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007972
Chris Lattnerecd79c62009-06-14 00:45:47 +00007973 // Read the base type.
7974 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007975 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007976 case 'v':
7977 assert(HowLong == 0 && !Signed && !Unsigned &&
7978 "Bad modifiers used with 'v'!");
7979 Type = Context.VoidTy;
7980 break;
Jack Carter24bef982013-08-15 15:16:57 +00007981 case 'h':
7982 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00007983 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00007984 Type = Context.HalfTy;
7985 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007986 case 'f':
7987 assert(HowLong == 0 && !Signed && !Unsigned &&
7988 "Bad modifiers used with 'f'!");
7989 Type = Context.FloatTy;
7990 break;
7991 case 'd':
7992 assert(HowLong < 2 && !Signed && !Unsigned &&
7993 "Bad modifiers used with 'd'!");
7994 if (HowLong)
7995 Type = Context.LongDoubleTy;
7996 else
7997 Type = Context.DoubleTy;
7998 break;
7999 case 's':
8000 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8001 if (Unsigned)
8002 Type = Context.UnsignedShortTy;
8003 else
8004 Type = Context.ShortTy;
8005 break;
8006 case 'i':
8007 if (HowLong == 3)
8008 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8009 else if (HowLong == 2)
8010 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8011 else if (HowLong == 1)
8012 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8013 else
8014 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8015 break;
8016 case 'c':
8017 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8018 if (Signed)
8019 Type = Context.SignedCharTy;
8020 else if (Unsigned)
8021 Type = Context.UnsignedCharTy;
8022 else
8023 Type = Context.CharTy;
8024 break;
8025 case 'b': // boolean
8026 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8027 Type = Context.BoolTy;
8028 break;
8029 case 'z': // size_t.
8030 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8031 Type = Context.getSizeType();
8032 break;
8033 case 'F':
8034 Type = Context.getCFConstantStringType();
8035 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008036 case 'G':
8037 Type = Context.getObjCIdType();
8038 break;
8039 case 'H':
8040 Type = Context.getObjCSelType();
8041 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008042 case 'M':
8043 Type = Context.getObjCSuperType();
8044 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008045 case 'a':
8046 Type = Context.getBuiltinVaListType();
8047 assert(!Type.isNull() && "builtin va list type not initialized!");
8048 break;
8049 case 'A':
8050 // This is a "reference" to a va_list; however, what exactly
8051 // this means depends on how va_list is defined. There are two
8052 // different kinds of va_list: ones passed by value, and ones
8053 // passed by reference. An example of a by-value va_list is
8054 // x86, where va_list is a char*. An example of by-ref va_list
8055 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8056 // we want this argument to be a char*&; for x86-64, we want
8057 // it to be a __va_list_tag*.
8058 Type = Context.getBuiltinVaListType();
8059 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008060 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008061 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008062 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008063 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008064 break;
8065 case 'V': {
8066 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008067 unsigned NumElements = strtoul(Str, &End, 10);
8068 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008069 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008070
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008071 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8072 RequiresICE, false);
8073 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008074
8075 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008076 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008077 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008078 break;
8079 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008080 case 'E': {
8081 char *End;
8082
8083 unsigned NumElements = strtoul(Str, &End, 10);
8084 assert(End != Str && "Missing vector size");
8085
8086 Str = End;
8087
8088 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8089 false);
8090 Type = Context.getExtVectorType(ElementType, NumElements);
8091 break;
8092 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008093 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008094 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8095 false);
8096 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008097 Type = Context.getComplexType(ElementType);
8098 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008099 }
8100 case 'Y' : {
8101 Type = Context.getPointerDiffType();
8102 break;
8103 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008104 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008105 Type = Context.getFILEType();
8106 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008107 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008108 return QualType();
8109 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008110 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008111 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008112 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008113 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008114 else
8115 Type = Context.getjmp_bufType();
8116
Mike Stump2adb4da2009-07-28 23:47:15 +00008117 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008118 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008119 return QualType();
8120 }
8121 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008122 case 'K':
8123 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8124 Type = Context.getucontext_tType();
8125
8126 if (Type.isNull()) {
8127 Error = ASTContext::GE_Missing_ucontext;
8128 return QualType();
8129 }
8130 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008131 case 'p':
8132 Type = Context.getProcessIDType();
8133 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008134 }
Mike Stump11289f42009-09-09 15:08:12 +00008135
Chris Lattnerdc226c22010-10-01 22:42:38 +00008136 // If there are modifiers and if we're allowed to parse them, go for it.
8137 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008138 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008139 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008140 default: Done = true; --Str; break;
8141 case '*':
8142 case '&': {
8143 // Both pointers and references can have their pointee types
8144 // qualified with an address space.
8145 char *End;
8146 unsigned AddrSpace = strtoul(Str, &End, 10);
8147 if (End != Str && AddrSpace != 0) {
8148 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8149 Str = End;
8150 }
8151 if (c == '*')
8152 Type = Context.getPointerType(Type);
8153 else
8154 Type = Context.getLValueReferenceType(Type);
8155 break;
8156 }
8157 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8158 case 'C':
8159 Type = Type.withConst();
8160 break;
8161 case 'D':
8162 Type = Context.getVolatileType(Type);
8163 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008164 case 'R':
8165 Type = Type.withRestrict();
8166 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008167 }
8168 }
Chris Lattner84733392010-10-01 07:13:18 +00008169
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008170 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008171 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008172
Chris Lattnerecd79c62009-06-14 00:45:47 +00008173 return Type;
8174}
8175
8176/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008177QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008178 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008179 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008180 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008181
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008182 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008183
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008184 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008185 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008186 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8187 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008188 if (Error != GE_None)
8189 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008190
8191 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8192
Chris Lattnerecd79c62009-06-14 00:45:47 +00008193 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008194 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008195 if (Error != GE_None)
8196 return QualType();
8197
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008198 // If this argument is required to be an IntegerConstantExpression and the
8199 // caller cares, fill in the bitmask we return.
8200 if (RequiresICE && IntegerConstantArgs)
8201 *IntegerConstantArgs |= 1 << ArgTypes.size();
8202
Chris Lattnerecd79c62009-06-14 00:45:47 +00008203 // Do array -> pointer decay. The builtin should use the decayed type.
8204 if (Ty->isArrayType())
8205 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008206
Chris Lattnerecd79c62009-06-14 00:45:47 +00008207 ArgTypes.push_back(Ty);
8208 }
8209
David Majnemerba3e5ec2015-03-13 18:26:17 +00008210 if (Id == Builtin::BI__GetExceptionInfo)
8211 return QualType();
8212
Chris Lattnerecd79c62009-06-14 00:45:47 +00008213 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8214 "'.' should only occur at end of builtin type list!");
8215
Reid Kleckner78af0702013-08-27 23:08:25 +00008216 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008217 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8218
8219 bool Variadic = (TypeStr[0] == '.');
8220
8221 // We really shouldn't be making a no-proto type here, especially in C++.
8222 if (ArgTypes.empty() && Variadic)
8223 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008224
John McCalldb40c7f2010-12-14 08:05:40 +00008225 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008226 EPI.ExtInfo = EI;
8227 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008228
Jordan Rose5c382722013-03-08 21:51:21 +00008229 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008230}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008231
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008232static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8233 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008234 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008235 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008236
Rafael Espindola3ae00052013-05-13 00:12:11 +00008237 GVALinkage External = GVA_StrongExternal;
8238 switch (FD->getTemplateSpecializationKind()) {
8239 case TSK_Undeclared:
8240 case TSK_ExplicitSpecialization:
8241 External = GVA_StrongExternal;
8242 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008243
Rafael Espindola3ae00052013-05-13 00:12:11 +00008244 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008245 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008246
David Majnemerc3d07332014-05-15 06:25:57 +00008247 // C++11 [temp.explicit]p10:
8248 // [ Note: The intent is that an inline function that is the subject of
8249 // an explicit instantiation declaration will still be implicitly
8250 // instantiated when used so that the body can be considered for
8251 // inlining, but that no out-of-line copy of the inline function would be
8252 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008253 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008254 return GVA_AvailableExternally;
8255
Rafael Espindola3ae00052013-05-13 00:12:11 +00008256 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008257 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008258 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008259 }
8260
8261 if (!FD->isInlined())
8262 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008263
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008264 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
8265 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008266 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008267 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8268
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008269 // GNU or C99 inline semantics. Determine whether this symbol should be
8270 // externally visible.
8271 if (FD->isInlineDefinitionExternallyVisible())
8272 return External;
8273
8274 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008275 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008276 }
8277
David Majnemer54e3ba52014-04-02 23:17:29 +00008278 // Functions specified with extern and inline in -fms-compatibility mode
8279 // forcibly get emitted. While the body of the function cannot be later
8280 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008281 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008282 return GVA_StrongODR;
8283
David Majnemer27d69db2014-04-28 22:17:59 +00008284 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008285}
8286
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008287static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
8288 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8289 // dllexport/dllimport on inline functions.
8290 if (D->hasAttr<DLLImportAttr>()) {
8291 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8292 return GVA_AvailableExternally;
8293 } else if (D->hasAttr<DLLExportAttr>()) {
8294 if (L == GVA_DiscardableODR)
8295 return GVA_StrongODR;
8296 }
8297 return L;
8298}
8299
8300GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8301 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
8302 FD);
8303}
8304
8305static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8306 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008307 if (!VD->isExternallyVisible())
8308 return GVA_Internal;
8309
David Majnemer27d69db2014-04-28 22:17:59 +00008310 if (VD->isStaticLocal()) {
8311 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8312 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8313 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8314 LexicalContext = LexicalContext->getLexicalParent();
8315
Richard Smith9e2341d2015-03-23 03:25:59 +00008316 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008317 // enclosing function.
8318 if (LexicalContext)
8319 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008320 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008321
8322 // GVA_StrongODR function linkage is stronger than what we need,
8323 // downgrade to GVA_DiscardableODR.
8324 // This allows us to discard the variable if we never end up needing it.
8325 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8326 : StaticLocalLinkage;
8327 }
8328
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008329 // MSVC treats in-class initialized static data members as definitions.
8330 // By giving them non-strong linkage, out-of-line definitions won't
8331 // cause link errors.
8332 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8333 return GVA_DiscardableODR;
8334
Richard Smith8809a0c2013-09-27 20:14:12 +00008335 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008336 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008337 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008338
David Majnemer6d1780c2015-07-17 23:36:49 +00008339 case TSK_ExplicitSpecialization:
8340 return Context.getLangOpts().MSVCCompat && VD->isStaticDataMember()
8341 ? GVA_StrongODR
8342 : GVA_StrongExternal;
8343
Rafael Espindola3ae00052013-05-13 00:12:11 +00008344 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008345 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008346
David Majnemer27d69db2014-04-28 22:17:59 +00008347 case TSK_ExplicitInstantiationDeclaration:
8348 return GVA_AvailableExternally;
8349
Rafael Espindola3ae00052013-05-13 00:12:11 +00008350 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008351 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008352 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008353
8354 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008355}
8356
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008357GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8358 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
8359 VD);
8360}
8361
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008362bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008363 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8364 if (!VD->isFileVarDecl())
8365 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008366 // Global named register variables (GNU extension) are never emitted.
8367 if (VD->getStorageClass() == SC_Register)
8368 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008369 if (VD->getDescribedVarTemplate() ||
8370 isa<VarTemplatePartialSpecializationDecl>(VD))
8371 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008372 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8373 // We never need to emit an uninstantiated function template.
8374 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8375 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008376 } else if (isa<OMPThreadPrivateDecl>(D))
8377 return true;
8378 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008379 return false;
8380
8381 // If this is a member of a class template, we do not need to emit it.
8382 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008383 return false;
8384
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008385 // Weak references don't produce any output by themselves.
8386 if (D->hasAttr<WeakRefAttr>())
8387 return false;
8388
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008389 // Aliases and used decls are required.
8390 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8391 return true;
8392
8393 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8394 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008395 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008396 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008397
8398 // Constructors and destructors are required.
8399 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8400 return true;
8401
John McCall6bd2a892013-01-25 22:31:03 +00008402 // The key function for a class is required. This rule only comes
8403 // into play when inline functions can be key functions, though.
8404 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8405 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8406 const CXXRecordDecl *RD = MD->getParent();
8407 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8408 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8409 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8410 return true;
8411 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008412 }
8413 }
8414
8415 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8416
8417 // static, static inline, always_inline, and extern inline functions can
8418 // always be deferred. Normal inline functions can be deferred in C99/C++.
8419 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008420 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8421 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008422 return false;
8423 return true;
8424 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008425
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008426 const VarDecl *VD = cast<VarDecl>(D);
8427 assert(VD->isFileVarDecl() && "Expected file scoped var");
8428
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008429 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8430 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008431 return false;
8432
Richard Smitha0e5e542012-11-12 21:38:00 +00008433 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008434 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008435 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8436 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008437 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008438
Richard Smitha0e5e542012-11-12 21:38:00 +00008439 // Variables that have destruction with side-effects are required.
8440 if (VD->getType().isDestructedType())
8441 return true;
8442
8443 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008444 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8445 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008446 return true;
8447
8448 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008449}
Charles Davis53c59df2010-08-16 03:33:14 +00008450
Reid Kleckner78af0702013-08-27 23:08:25 +00008451CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8452 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008453 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008454 if (IsCXXMethod)
8455 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008456
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008457 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8458
8459 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008460}
8461
Jay Foad39c79802011-01-12 09:06:06 +00008462bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008463 // Pass through to the C++ ABI object
8464 return ABI->isNearlyEmpty(RD);
8465}
8466
Reid Kleckner96f8f932014-02-05 17:27:08 +00008467VTableContextBase *ASTContext::getVTableContext() {
8468 if (!VTContext.get()) {
8469 if (Target->getCXXABI().isMicrosoft())
8470 VTContext.reset(new MicrosoftVTableContext(*this));
8471 else
8472 VTContext.reset(new ItaniumVTableContext(*this));
8473 }
8474 return VTContext.get();
8475}
8476
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008477MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008478 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008479 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008480 case TargetCXXABI::GenericItanium:
8481 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008482 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008483 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008484 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008485 case TargetCXXABI::WebAssembly:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008486 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008487 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008488 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008489 }
David Blaikie83d382b2011-09-23 05:06:16 +00008490 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008491}
8492
Charles Davis53c59df2010-08-16 03:33:14 +00008493CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008494
8495size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008496 return ASTRecordLayouts.getMemorySize() +
8497 llvm::capacity_in_bytes(ObjCLayouts) +
8498 llvm::capacity_in_bytes(KeyFunctions) +
8499 llvm::capacity_in_bytes(ObjCImpls) +
8500 llvm::capacity_in_bytes(BlockVarCopyInits) +
8501 llvm::capacity_in_bytes(DeclAttrs) +
8502 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8503 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8504 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8505 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8506 llvm::capacity_in_bytes(OverriddenMethods) +
8507 llvm::capacity_in_bytes(Types) +
8508 llvm::capacity_in_bytes(VariableArrayTypes) +
8509 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008510}
Ted Kremenek540017e2011-10-06 05:00:56 +00008511
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008512/// getIntTypeForBitwidth -
8513/// sets integer QualTy according to specified details:
8514/// bitwidth, signed/unsigned.
8515/// Returns empty type if there is no appropriate target types.
8516QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8517 unsigned Signed) const {
8518 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8519 CanQualType QualTy = getFromTargetType(Ty);
8520 if (!QualTy && DestWidth == 128)
8521 return Signed ? Int128Ty : UnsignedInt128Ty;
8522 return QualTy;
8523}
8524
8525/// getRealTypeForBitwidth -
8526/// sets floating point QualTy according to specified bitwidth.
8527/// Returns empty type if there is no appropriate target types.
8528QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8529 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8530 switch (Ty) {
8531 case TargetInfo::Float:
8532 return FloatTy;
8533 case TargetInfo::Double:
8534 return DoubleTy;
8535 case TargetInfo::LongDouble:
8536 return LongDoubleTy;
8537 case TargetInfo::NoFloat:
8538 return QualType();
8539 }
8540
8541 llvm_unreachable("Unhandled TargetInfo::RealType value");
8542}
8543
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008544void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8545 if (Number > 1)
8546 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008547}
8548
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008549unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8550 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8551 MangleNumbers.find(ND);
8552 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008553}
8554
David Majnemer2206bf52014-03-05 08:57:59 +00008555void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8556 if (Number > 1)
8557 StaticLocalNumbers[VD] = Number;
8558}
8559
8560unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8561 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8562 StaticLocalNumbers.find(VD);
8563 return I != StaticLocalNumbers.end() ? I->second : 1;
8564}
8565
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008566MangleNumberingContext &
8567ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008568 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8569 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8570 if (!MCtx)
8571 MCtx = createMangleNumberingContext();
8572 return *MCtx;
8573}
8574
8575MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8576 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008577}
8578
David Majnemere7a818f2015-03-06 18:53:55 +00008579const CXXConstructorDecl *
8580ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8581 return ABI->getCopyConstructorForExceptionObject(
8582 cast<CXXRecordDecl>(RD->getFirstDecl()));
8583}
8584
8585void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8586 CXXConstructorDecl *CD) {
8587 return ABI->addCopyConstructorForExceptionObject(
8588 cast<CXXRecordDecl>(RD->getFirstDecl()),
8589 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8590}
8591
David Majnemerdfa6d202015-03-11 18:36:39 +00008592void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8593 unsigned ParmIdx, Expr *DAE) {
8594 ABI->addDefaultArgExprForConstructor(
8595 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8596}
8597
8598Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8599 unsigned ParmIdx) {
8600 return ABI->getDefaultArgExprForConstructor(
8601 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8602}
8603
David Majnemer00350522015-08-31 18:48:39 +00008604void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8605 TypedefNameDecl *DD) {
8606 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8607}
8608
8609TypedefNameDecl *
8610ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8611 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8612}
8613
8614void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8615 DeclaratorDecl *DD) {
8616 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8617}
8618
8619DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8620 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8621}
8622
Ted Kremenek540017e2011-10-06 05:00:56 +00008623void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8624 ParamIndices[D] = index;
8625}
8626
8627unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8628 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8629 assert(I != ParamIndices.end() &&
8630 "ParmIndices lacks entry set by ParmVarDecl");
8631 return I->second;
8632}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008633
Richard Smithe6c01442013-06-05 00:46:14 +00008634APValue *
8635ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8636 bool MayCreate) {
8637 assert(E && E->getStorageDuration() == SD_Static &&
8638 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008639 if (MayCreate) {
8640 APValue *&MTVI = MaterializedTemporaryValues[E];
8641 if (!MTVI)
8642 MTVI = new (*this) APValue;
8643 return MTVI;
8644 }
Richard Smithe6c01442013-06-05 00:46:14 +00008645
David Majnemer2dcef9e2015-08-13 23:50:15 +00008646 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008647}
8648
Fariborz Jahanian615de762013-05-28 17:37:39 +00008649bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8650 const llvm::Triple &T = getTargetInfo().getTriple();
8651 if (!T.isOSDarwin())
8652 return false;
8653
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008654 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8655 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8656 return false;
8657
Fariborz Jahanian615de762013-05-28 17:37:39 +00008658 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8659 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8660 uint64_t Size = sizeChars.getQuantity();
8661 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8662 unsigned Align = alignChars.getQuantity();
8663 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8664 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8665}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008666
8667namespace {
8668
8669 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8670 /// parents as defined by the \c RecursiveASTVisitor.
8671 ///
8672 /// Note that the relationship described here is purely in terms of AST
8673 /// traversal - there are other relationships (for example declaration context)
8674 /// in the AST that are better modeled by special matchers.
8675 ///
8676 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8677 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8678
8679 public:
8680 /// \brief Builds and returns the translation unit's parent map.
8681 ///
8682 /// The caller takes ownership of the returned \c ParentMap.
8683 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8684 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8685 Visitor.TraverseDecl(&TU);
8686 return Visitor.Parents;
8687 }
8688
8689 private:
8690 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8691
8692 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8693 }
8694
8695 bool shouldVisitTemplateInstantiations() const {
8696 return true;
8697 }
8698 bool shouldVisitImplicitCode() const {
8699 return true;
8700 }
8701 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8702 // are not triggered during data recursion.
8703 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8704 return false;
8705 }
8706
8707 template <typename T>
8708 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
Craig Topper36250ad2014-05-12 05:36:57 +00008709 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008710 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008711 if (ParentStack.size() > 0) {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008712 // FIXME: Currently we add the same parent multiple times, but only
8713 // when no memoization data is available for the type.
8714 // For example when we visit all subexpressions of template
8715 // instantiations; this is suboptimal, but benign: the only way to
8716 // visit those is with hasAncestor / hasParent, and those do not create
8717 // new matches.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008718 // The plan is to enable DynTypedNode to be storable in a map or hash
8719 // map. The main problem there is to implement hash functions /
8720 // comparison operators for all types that DynTypedNode supports that
8721 // do not have pointer identity.
Manuel Klimek95403e62014-05-21 13:28:59 +00008722 auto &NodeOrVector = (*Parents)[Node];
8723 if (NodeOrVector.isNull()) {
8724 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008725 } else {
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008726 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8727 auto *Node =
8728 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8729 auto *Vector = new ASTContext::ParentVector(1, *Node);
8730 NodeOrVector = Vector;
8731 delete Node;
8732 }
Manuel Klimek95403e62014-05-21 13:28:59 +00008733 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008734
8735 auto *Vector =
8736 NodeOrVector.template get<ASTContext::ParentVector *>();
8737 // Skip duplicates for types that have memoization data.
8738 // We must check that the type has memoization data before calling
8739 // std::find() because DynTypedNode::operator== can't compare all
8740 // types.
8741 bool Found = ParentStack.back().getMemoizationData() &&
8742 std::find(Vector->begin(), Vector->end(),
8743 ParentStack.back()) != Vector->end();
8744 if (!Found)
8745 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008746 }
8747 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008748 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8749 bool Result = (this ->* traverse) (Node);
8750 ParentStack.pop_back();
8751 return Result;
8752 }
8753
8754 bool TraverseDecl(Decl *DeclNode) {
8755 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8756 }
8757
8758 bool TraverseStmt(Stmt *StmtNode) {
8759 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8760 }
8761
8762 ASTContext::ParentMap *Parents;
8763 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8764
8765 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8766 };
8767
8768} // end namespace
8769
Benjamin Kramer07935292014-10-04 17:01:26 +00008770ArrayRef<ast_type_traits::DynTypedNode>
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008771ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8772 assert(Node.getMemoizationData() &&
8773 "Invariant broken: only nodes that support memoization may be "
8774 "used in the parent map.");
8775 if (!AllParents) {
8776 // We always need to run over the whole translation unit, as
8777 // hasAncestor can escape any subtree.
8778 AllParents.reset(
8779 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8780 }
8781 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8782 if (I == AllParents->end()) {
Benjamin Kramer07935292014-10-04 17:01:26 +00008783 return None;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008784 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008785 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8786 return llvm::makeArrayRef(N, 1);
Manuel Klimek95403e62014-05-21 13:28:59 +00008787 }
Benjamin Kramer07935292014-10-04 17:01:26 +00008788 return *I->second.get<ParentVector *>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008789}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008790
8791bool
8792ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8793 const ObjCMethodDecl *MethodImpl) {
8794 // No point trying to match an unavailable/deprecated mothod.
8795 if (MethodDecl->hasAttr<UnavailableAttr>()
8796 || MethodDecl->hasAttr<DeprecatedAttr>())
8797 return false;
8798 if (MethodDecl->getObjCDeclQualifier() !=
8799 MethodImpl->getObjCDeclQualifier())
8800 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008801 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008802 return false;
8803
8804 if (MethodDecl->param_size() != MethodImpl->param_size())
8805 return false;
8806
8807 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8808 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8809 EF = MethodDecl->param_end();
8810 IM != EM && IF != EF; ++IM, ++IF) {
8811 const ParmVarDecl *DeclVar = (*IF);
8812 const ParmVarDecl *ImplVar = (*IM);
8813 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8814 return false;
8815 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8816 return false;
8817 }
8818 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8819
8820}
Richard Smith053f6c62014-05-16 23:01:30 +00008821
8822// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8823// doesn't include ASTContext.h
8824template
8825clang::LazyGenerationalUpdatePtr<
8826 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8827clang::LazyGenerationalUpdatePtr<
8828 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8829 const clang::ASTContext &Ctx, Decl *Value);