blob: 0c30df091302e621ffe6b6d4babdba5e389d7c80 [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) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000372 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373 } else
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 if (RC)
378 break;
379 }
380 }
381
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000384
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000385 if (OriginalDecl)
386 *OriginalDecl = OriginalDeclForRC;
387
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
390 Raw.setRaw(RC);
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000393
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397 R = Raw;
398 }
399
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400 return RC;
401}
402
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 if (!ID)
409 return;
410 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000411 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000413 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
416 }
417 }
418}
419
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000420comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
431 ThisDeclInfo);
432 return CFC;
433
434}
435
Richard Smithb39b9d52013-05-21 05:24:00 +0000436comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
437 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000438 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000439}
440
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000441comments::FullComment *ASTContext::getCommentForDecl(
442 const Decl *D,
443 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000444 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000445 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000446 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000447
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000448 const Decl *Canonical = D->getCanonicalDecl();
449 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
450 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000451
452 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000453 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000455 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000456 return CFC;
457 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000458 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000459 }
460
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000463 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000464 if (!RC) {
465 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000466 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000467 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000468 if (OMD && OMD->isPropertyAccessor())
469 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
470 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
471 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000472 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000473 addRedeclaredMethods(OMD, Overridden);
474 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000475 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
476 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
477 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000478 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000479 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000480 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000481 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000482 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000483 if (const TagType *TT = QT->getAs<TagType>())
484 if (const Decl *TD = TT->getDecl())
485 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000486 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000487 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000488 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
489 while (IC->getSuperClass()) {
490 IC = IC->getSuperClass();
491 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
492 return cloneFullComment(FC, D);
493 }
494 }
495 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
496 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
497 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
498 return cloneFullComment(FC, D);
499 }
500 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
501 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000502 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000503 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000504 for (const auto &I : RD->bases()) {
505 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000507 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000508 if (Ty.isNull())
509 continue;
510 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
511 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
512 continue;
513
514 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
515 return cloneFullComment(FC, D);
516 }
517 }
518 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000519 for (const auto &I : RD->vbases()) {
520 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000521 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000522 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000523 if (Ty.isNull())
524 continue;
525 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
526 if (!(VirtualBase= VirtualBase->getDefinition()))
527 continue;
528 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
529 return cloneFullComment(FC, D);
530 }
531 }
532 }
Craig Topper36250ad2014-05-12 05:36:57 +0000533 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000534 }
535
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000536 // If the RawComment was attached to other redeclaration of this Decl, we
537 // should parse the comment in context of that other Decl. This is important
538 // because comments can contain references to parameter names which can be
539 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000540 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000541 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000542
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000543 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000544 ParsedComments[Canonical] = FC;
545 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000546}
547
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000548void
549ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
550 TemplateTemplateParmDecl *Parm) {
551 ID.AddInteger(Parm->getDepth());
552 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000553 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000554
555 TemplateParameterList *Params = Parm->getTemplateParameters();
556 ID.AddInteger(Params->size());
557 for (TemplateParameterList::const_iterator P = Params->begin(),
558 PEnd = Params->end();
559 P != PEnd; ++P) {
560 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
561 ID.AddInteger(0);
562 ID.AddBoolean(TTP->isParameterPack());
563 continue;
564 }
565
566 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
567 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000568 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000569 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000570 if (NTTP->isExpandedParameterPack()) {
571 ID.AddBoolean(true);
572 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000573 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
574 QualType T = NTTP->getExpansionType(I);
575 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
576 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000577 } else
578 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000579 continue;
580 }
581
582 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
583 ID.AddInteger(2);
584 Profile(ID, TTP);
585 }
586}
587
588TemplateTemplateParmDecl *
589ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000590 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000591 // Check if we already have a canonical template template parameter.
592 llvm::FoldingSetNodeID ID;
593 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000594 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000595 CanonicalTemplateTemplateParm *Canonical
596 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
597 if (Canonical)
598 return Canonical->getParam();
599
600 // Build a canonical template parameter list.
601 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000602 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000603 CanonParams.reserve(Params->size());
604 for (TemplateParameterList::const_iterator P = Params->begin(),
605 PEnd = Params->end();
606 P != PEnd; ++P) {
607 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
608 CanonParams.push_back(
609 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000610 SourceLocation(),
611 SourceLocation(),
612 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000613 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000614 TTP->isParameterPack()));
615 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000616 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
617 QualType T = getCanonicalType(NTTP->getType());
618 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
619 NonTypeTemplateParmDecl *Param;
620 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000621 SmallVector<QualType, 2> ExpandedTypes;
622 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000623 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
624 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
625 ExpandedTInfos.push_back(
626 getTrivialTypeSourceInfo(ExpandedTypes.back()));
627 }
628
629 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000630 SourceLocation(),
631 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000632 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000633 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000634 T,
635 TInfo,
636 ExpandedTypes.data(),
637 ExpandedTypes.size(),
638 ExpandedTInfos.data());
639 } else {
640 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000641 SourceLocation(),
642 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000644 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000645 T,
646 NTTP->isParameterPack(),
647 TInfo);
648 }
649 CanonParams.push_back(Param);
650
651 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000652 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
653 cast<TemplateTemplateParmDecl>(*P)));
654 }
655
656 TemplateTemplateParmDecl *CanonTTP
657 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
658 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000659 TTP->getPosition(),
660 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000661 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000662 TemplateParameterList::Create(*this, SourceLocation(),
663 SourceLocation(),
664 CanonParams.data(),
665 CanonParams.size(),
666 SourceLocation()));
667
668 // Get the new insert position for the node we care about.
669 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000670 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000671 (void)Canonical;
672
673 // Create the canonical template template parameter entry.
674 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
675 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
676 return CanonTTP;
677}
678
Charles Davis53c59df2010-08-16 03:33:14 +0000679CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000680 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000681
John McCall359b8852013-01-25 22:30:49 +0000682 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000683 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000684 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000685 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000686 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000687 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000688 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000689 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000690 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000691 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000692 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000693 return CreateMicrosoftCXXABI(*this);
694 }
David Blaikie8a40f702012-01-17 06:56:22 +0000695 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000696}
697
Douglas Gregore8bbc122011-09-02 00:18:52 +0000698static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000699 const LangOptions &LOpts) {
700 if (LOpts.FakeAddressSpaceMap) {
701 // The fake address space map must have a distinct entry for each
702 // language-specific address space.
703 static const unsigned FakeAddrSpaceMap[] = {
704 1, // opencl_global
705 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000706 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000707 4, // opencl_generic
708 5, // cuda_device
709 6, // cuda_constant
710 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000711 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000712 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000713 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000715 }
716}
717
David Tweed31d09b02013-09-13 12:04:22 +0000718static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
719 const LangOptions &LangOpts) {
720 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000721 case LangOptions::ASMM_Target:
722 return TI.useAddressSpaceMapMangling();
723 case LangOptions::ASMM_On:
724 return true;
725 case LangOptions::ASMM_Off:
726 return false;
727 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000728 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000729}
730
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000731ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000732 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000733 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000734 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
735 DependentTemplateSpecializationTypes(this_()),
736 SubstTemplateTemplateParmPacks(this_()),
737 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
738 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000739 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
740 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
741 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000742 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
743 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
744 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
745 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
Richard Smithf19e1272015-03-07 00:04:49 +0000746 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000747 MakeIntegerSeqDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000748 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000749 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
750 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
751 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
752 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000753 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000754 TUDecl = TranslationUnitDecl::Create(*this);
755}
756
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000757ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000758 ReleaseParentMapEntries();
759
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000760 // Release the DenseMaps associated with DeclContext objects.
761 // FIXME: Is this the ideal solution?
762 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000763
Manuel Klimeka7328992013-06-03 13:51:33 +0000764 // Call all of the deallocation functions on all of their targets.
765 for (DeallocationMap::const_iterator I = Deallocations.begin(),
766 E = Deallocations.end(); I != E; ++I)
767 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
768 (I->first)((I->second)[J]);
769
Ted Kremenek076baeb2010-06-08 23:00:58 +0000770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000771 // because they can contain DenseMaps.
772 for (llvm::DenseMap<const ObjCContainerDecl*,
773 const ASTRecordLayout*>::iterator
774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778
Ted Kremenek076baeb2010-06-08 23:00:58 +0000779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
781 // Increment in loop to prevent using deallocated memory.
782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
783 R->Destroy(*this);
784 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000785
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
788 A != AEnd; ++A)
789 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000790
David Majnemere694f3e2015-08-14 14:43:50 +0000791 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
792 MaterializedTemporaryValues)
793 MTVPair.second->~APValue();
794
Reid Kleckner588c9372014-02-19 23:44:52 +0000795 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000796}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000797
Manuel Klimek95403e62014-05-21 13:28:59 +0000798void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000799 if (!PointerParents) return;
800 for (const auto &Entry : *PointerParents) {
801 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
802 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
803 } else if (Entry.second.is<ParentVector *>()) {
804 delete Entry.second.get<ParentVector *>();
805 }
806 }
807 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000808 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
809 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000810 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000811 delete Entry.second.get<ParentVector *>();
812 }
813 }
814}
815
Douglas Gregor1a809332010-05-23 18:26:36 +0000816void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000817 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000818}
819
Mike Stump11289f42009-09-09 15:08:12 +0000820void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000821ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
822 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000823}
824
Chris Lattner4eb445d2007-01-26 01:27:23 +0000825void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000826 llvm::errs() << "\n*** AST Context Stats:\n";
827 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000828
Douglas Gregora30d0462009-05-26 14:40:08 +0000829 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000830#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000831#define ABSTRACT_TYPE(Name, Parent)
832#include "clang/AST/TypeNodes.def"
833 0 // Extra
834 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000835
Chris Lattner4eb445d2007-01-26 01:27:23 +0000836 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
837 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000838 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000839 }
840
Douglas Gregora30d0462009-05-26 14:40:08 +0000841 unsigned Idx = 0;
842 unsigned TotalBytes = 0;
843#define TYPE(Name, Parent) \
844 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000845 llvm::errs() << " " << counts[Idx] << " " << #Name \
846 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000847 TotalBytes += counts[Idx] * sizeof(Name##Type); \
848 ++Idx;
849#define ABSTRACT_TYPE(Name, Parent)
850#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chandler Carruth3c147a72011-07-04 05:32:14 +0000852 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
853
Douglas Gregor7454c562010-07-02 20:37:36 +0000854 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000855 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
856 << NumImplicitDefaultConstructors
857 << " implicit default constructors created\n";
858 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
859 << NumImplicitCopyConstructors
860 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000861 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000862 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
863 << NumImplicitMoveConstructors
864 << " implicit move constructors created\n";
865 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
866 << NumImplicitCopyAssignmentOperators
867 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000868 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000869 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
870 << NumImplicitMoveAssignmentOperators
871 << " implicit move assignment operators created\n";
872 llvm::errs() << NumImplicitDestructorsDeclared << "/"
873 << NumImplicitDestructors
874 << " implicit destructors created\n";
875
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000876 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000877 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000878 ExternalSource->PrintStats();
879 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000880
Douglas Gregor5b11d492010-07-25 17:53:33 +0000881 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000882}
883
Richard Smith42413142015-05-15 20:05:43 +0000884void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
885 bool NotifyListeners) {
886 if (NotifyListeners)
887 if (auto *Listener = getASTMutationListener())
888 Listener->RedefinedHiddenDefinition(ND, M);
889
890 if (getLangOpts().ModulesLocalVisibility)
891 MergedDefModules[ND].push_back(M);
892 else
893 ND->setHidden(false);
894}
895
896void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
897 auto It = MergedDefModules.find(ND);
898 if (It == MergedDefModules.end())
899 return;
900
901 auto &Merged = It->second;
902 llvm::DenseSet<Module*> Found;
903 for (Module *&M : Merged)
904 if (!Found.insert(M).second)
905 M = nullptr;
906 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
907}
908
Richard Smithf19e1272015-03-07 00:04:49 +0000909ExternCContextDecl *ASTContext::getExternCContextDecl() const {
910 if (!ExternCContext)
911 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
912
913 return ExternCContext;
914}
915
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000916BuiltinTemplateDecl *
917ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
918 const IdentifierInfo *II) const {
919 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
920 BuiltinTemplate->setImplicit();
921 TUDecl->addDecl(BuiltinTemplate);
922
923 return BuiltinTemplate;
924}
925
926BuiltinTemplateDecl *
927ASTContext::getMakeIntegerSeqDecl() const {
928 if (!MakeIntegerSeqDecl)
929 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
930 getMakeIntegerSeqName());
931 return MakeIntegerSeqDecl;
932}
933
Alp Toker2dea15b2013-12-17 01:22:38 +0000934RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
935 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000936 SourceLocation Loc;
937 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000938 if (getLangOpts().CPlusPlus)
939 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
940 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000941 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000942 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
943 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000944 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000945 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
946 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000947 return NewDecl;
948}
949
950TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
951 StringRef Name) const {
952 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
953 TypedefDecl *NewDecl = TypedefDecl::Create(
954 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
955 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
956 NewDecl->setImplicit();
957 return NewDecl;
958}
959
Douglas Gregor801c99d2011-08-12 06:49:56 +0000960TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000961 if (!Int128Decl)
962 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000963 return Int128Decl;
964}
965
966TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000967 if (!UInt128Decl)
968 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000969 return UInt128Decl;
970}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000971
Nico Webere1687c52013-06-20 21:44:55 +0000972TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000973 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000974 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000975 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000976
Nico Webere1687c52013-06-20 21:44:55 +0000977 return Float128StubDecl;
978}
979
John McCall48f2d582009-10-23 23:03:21 +0000980void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000981 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000982 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000983 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000984}
985
Artem Belevichb5bc9232015-09-22 17:23:22 +0000986void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
987 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000988 assert((!this->Target || this->Target == &Target) &&
989 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000990 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000991
Douglas Gregore8bbc122011-09-02 00:18:52 +0000992 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000993 this->AuxTarget = AuxTarget;
994
Douglas Gregore8bbc122011-09-02 00:18:52 +0000995 ABI.reset(createCXXABI(Target));
996 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000997 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000998
Chris Lattner970e54e2006-11-12 00:37:36 +0000999 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001000 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001001
Chris Lattner970e54e2006-11-12 00:37:36 +00001002 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001003 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001004 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001005 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001006 InitBuiltinType(CharTy, BuiltinType::Char_S);
1007 else
1008 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001009 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001010 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1011 InitBuiltinType(ShortTy, BuiltinType::Short);
1012 InitBuiltinType(IntTy, BuiltinType::Int);
1013 InitBuiltinType(LongTy, BuiltinType::Long);
1014 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001015
Chris Lattner970e54e2006-11-12 00:37:36 +00001016 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001017 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1018 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1019 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1020 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1021 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattner970e54e2006-11-12 00:37:36 +00001023 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001024 InitBuiltinType(FloatTy, BuiltinType::Float);
1025 InitBuiltinType(DoubleTy, BuiltinType::Double);
1026 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001027
Chris Lattnerf122cef2009-04-30 02:43:43 +00001028 // GNU extension, 128-bit integers.
1029 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1030 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1031
Hans Wennborg0d81e012013-05-10 10:08:40 +00001032 // C++ 3.9.1p5
1033 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1034 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1035 else // -fshort-wchar makes wchar_t be unsigned.
1036 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1037 if (LangOpts.CPlusPlus && LangOpts.WChar)
1038 WideCharTy = WCharTy;
1039 else {
1040 // C99 (or C++ using -fno-wchar).
1041 WideCharTy = getFromTargetType(Target.getWCharType());
1042 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001043
James Molloy36365542012-05-04 10:55:22 +00001044 WIntTy = getFromTargetType(Target.getWIntType());
1045
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001046 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1047 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1048 else // C99
1049 Char16Ty = getFromTargetType(Target.getChar16Type());
1050
1051 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1052 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1053 else // C99
1054 Char32Ty = getFromTargetType(Target.getChar32Type());
1055
Douglas Gregor4619e432008-12-05 23:32:09 +00001056 // Placeholder type for type-dependent expressions whose type is
1057 // completely unknown. No code should ever check a type against
1058 // DependentTy and users should never see it; however, it is here to
1059 // help diagnose failures to properly check for type-dependent
1060 // expressions.
1061 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062
John McCall36e7fe32010-10-12 00:20:44 +00001063 // Placeholder type for functions.
1064 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1065
John McCall0009fcc2011-04-26 20:42:42 +00001066 // Placeholder type for bound members.
1067 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1068
John McCall526ab472011-10-25 17:37:35 +00001069 // Placeholder type for pseudo-objects.
1070 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1071
John McCall31996342011-04-07 08:22:57 +00001072 // "any" type; useful for debugger-like clients.
1073 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1074
John McCall8a6b59a2011-10-17 18:09:15 +00001075 // Placeholder type for unbridged ARC casts.
1076 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1077
Eli Friedman34866c72012-08-31 00:14:07 +00001078 // Placeholder type for builtin functions.
1079 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1080
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001081 // Placeholder type for OMP array sections.
1082 if (LangOpts.OpenMP)
1083 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1084
Chris Lattner970e54e2006-11-12 00:37:36 +00001085 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001086 FloatComplexTy = getComplexType(FloatTy);
1087 DoubleComplexTy = getComplexType(DoubleTy);
1088 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001089
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001090 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001091 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1092 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001093 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001094
1095 if (LangOpts.OpenCL) {
1096 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1097 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1098 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1099 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1100 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001101 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1102 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1103 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1104 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1105 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1106 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1107 BuiltinType::OCLImage2dArrayMSAADepth);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001108 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001109
Guy Benyei61054192013-02-07 10:55:47 +00001110 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001111 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001112 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1113 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1114 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1115 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001116 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001117
1118 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001119 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1120 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001121
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001122 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001123
1124 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001125
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001126 // void * type
1127 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001128
1129 // nullptr type (C++0x 2.14.7)
1130 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001131
1132 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1133 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001134
1135 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001136 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001137}
1138
David Blaikie9c902b52011-09-25 23:23:43 +00001139DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001140 return SourceMgr.getDiagnostics();
1141}
1142
Douglas Gregor561eceb2010-08-30 16:49:28 +00001143AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1144 AttrVec *&Result = DeclAttrs[D];
1145 if (!Result) {
1146 void *Mem = Allocate(sizeof(AttrVec));
1147 Result = new (Mem) AttrVec;
1148 }
1149
1150 return *Result;
1151}
1152
1153/// \brief Erase the attributes corresponding to the given declaration.
1154void ASTContext::eraseDeclAttrs(const Decl *D) {
1155 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1156 if (Pos != DeclAttrs.end()) {
1157 Pos->second->~AttrVec();
1158 DeclAttrs.erase(Pos);
1159 }
1160}
1161
Larisse Voufo39a1e502013-08-06 01:03:05 +00001162// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001163MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001164ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001165 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001166 return getTemplateOrSpecializationInfo(Var)
1167 .dyn_cast<MemberSpecializationInfo *>();
1168}
1169
1170ASTContext::TemplateOrSpecializationInfo
1171ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1172 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1173 TemplateOrInstantiation.find(Var);
1174 if (Pos == TemplateOrInstantiation.end())
1175 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001176
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001177 return Pos->second;
1178}
1179
Mike Stump11289f42009-09-09 15:08:12 +00001180void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001181ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001182 TemplateSpecializationKind TSK,
1183 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001184 assert(Inst->isStaticDataMember() && "Not a static data member");
1185 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001186 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1187 Tmpl, TSK, PointOfInstantiation));
1188}
1189
1190void
1191ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1192 TemplateOrSpecializationInfo TSI) {
1193 assert(!TemplateOrInstantiation[Inst] &&
1194 "Already noted what the variable was instantiated from");
1195 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001196}
1197
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001198FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1199 const FunctionDecl *FD){
1200 assert(FD && "Specialization is 0");
1201 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001202 = ClassScopeSpecializationPattern.find(FD);
1203 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001204 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001205
1206 return Pos->second;
1207}
1208
1209void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1210 FunctionDecl *Pattern) {
1211 assert(FD && "Specialization is 0");
1212 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001213 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001214}
1215
John McCalle61f2ba2009-11-18 02:36:19 +00001216NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001217ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001218 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001219 = InstantiatedFromUsingDecl.find(UUD);
1220 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001221 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001222
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001223 return Pos->second;
1224}
1225
1226void
John McCallb96ec562009-12-04 22:46:56 +00001227ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1228 assert((isa<UsingDecl>(Pattern) ||
1229 isa<UnresolvedUsingValueDecl>(Pattern) ||
1230 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1231 "pattern decl is not a using decl");
1232 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1233 InstantiatedFromUsingDecl[Inst] = Pattern;
1234}
1235
1236UsingShadowDecl *
1237ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1238 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1239 = InstantiatedFromUsingShadowDecl.find(Inst);
1240 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001241 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001242
1243 return Pos->second;
1244}
1245
1246void
1247ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1248 UsingShadowDecl *Pattern) {
1249 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1250 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001251}
1252
Anders Carlsson5da84842009-09-01 04:26:58 +00001253FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1254 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1255 = InstantiatedFromUnnamedFieldDecl.find(Field);
1256 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001257 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001258
Anders Carlsson5da84842009-09-01 04:26:58 +00001259 return Pos->second;
1260}
1261
1262void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1263 FieldDecl *Tmpl) {
1264 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1265 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1266 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1267 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001268
Anders Carlsson5da84842009-09-01 04:26:58 +00001269 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1270}
1271
Douglas Gregor832940b2010-03-02 23:58:15 +00001272ASTContext::overridden_cxx_method_iterator
1273ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1274 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001275 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001276 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001277 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001278
1279 return Pos->second.begin();
1280}
1281
1282ASTContext::overridden_cxx_method_iterator
1283ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1284 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001285 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001286 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001287 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001288
1289 return Pos->second.end();
1290}
1291
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001292unsigned
1293ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1294 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001295 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001296 if (Pos == OverriddenMethods.end())
1297 return 0;
1298
1299 return Pos->second.size();
1300}
1301
Douglas Gregor832940b2010-03-02 23:58:15 +00001302void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1303 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001304 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001305 OverriddenMethods[Method].push_back(Overridden);
1306}
1307
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001308void ASTContext::getOverriddenMethods(
1309 const NamedDecl *D,
1310 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001311 assert(D);
1312
1313 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001314 Overridden.append(overridden_methods_begin(CXXMethod),
1315 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001316 return;
1317 }
1318
1319 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1320 if (!Method)
1321 return;
1322
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001323 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1324 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001325 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001326}
1327
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001328void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1329 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1330 assert(!Import->isFromASTFile() && "Non-local import declaration");
1331 if (!FirstLocalImport) {
1332 FirstLocalImport = Import;
1333 LastLocalImport = Import;
1334 return;
1335 }
1336
1337 LastLocalImport->NextLocalImport = Import;
1338 LastLocalImport = Import;
1339}
1340
Chris Lattner53cfe802007-07-18 17:52:12 +00001341//===----------------------------------------------------------------------===//
1342// Type Sizing and Analysis
1343//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001344
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001345/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1346/// scalar floating point type.
1347const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001348 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001349 assert(BT && "Not a floating point type!");
1350 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001351 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001352 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001353 case BuiltinType::Float: return Target->getFloatFormat();
1354 case BuiltinType::Double: return Target->getDoubleFormat();
1355 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001356 }
1357}
1358
Rafael Espindola71eccb32013-08-08 19:53:46 +00001359CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001360 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001361
John McCall94268702010-10-08 18:24:19 +00001362 bool UseAlignAttrOnly = false;
1363 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1364 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001365
John McCall94268702010-10-08 18:24:19 +00001366 // __attribute__((aligned)) can increase or decrease alignment
1367 // *except* on a struct or struct member, where it only increases
1368 // alignment unless 'packed' is also specified.
1369 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001370 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001371 // ignore that possibility; Sema should diagnose it.
1372 if (isa<FieldDecl>(D)) {
1373 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1374 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1375 } else {
1376 UseAlignAttrOnly = true;
1377 }
1378 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001379 else if (isa<FieldDecl>(D))
1380 UseAlignAttrOnly =
1381 D->hasAttr<PackedAttr>() ||
1382 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001383
John McCall4e819612011-01-20 07:57:12 +00001384 // If we're using the align attribute only, just ignore everything
1385 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001386 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001387 // do nothing
1388
John McCall94268702010-10-08 18:24:19 +00001389 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001390 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001391 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001392 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001393 T = RT->getPointeeType();
1394 else
1395 T = getPointerType(RT->getPointeeType());
1396 }
Richard Smithf6d70302014-06-10 23:34:28 +00001397 QualType BaseT = getBaseElementType(T);
1398 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001399 // Adjust alignments of declarations with array type by the
1400 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001401 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001402 unsigned MinWidth = Target->getLargeArrayMinWidth();
1403 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001404 if (isa<VariableArrayType>(arrayType))
1405 Align = std::max(Align, Target->getLargeArrayAlign());
1406 else if (isa<ConstantArrayType>(arrayType) &&
1407 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1408 Align = std::max(Align, Target->getLargeArrayAlign());
1409 }
John McCall33ddac02011-01-19 10:06:00 +00001410 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001411 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001412 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001413 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001414 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1415 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001416 }
John McCall4e819612011-01-20 07:57:12 +00001417
1418 // Fields can be subject to extra alignment constraints, like if
1419 // the field is packed, the struct is packed, or the struct has a
1420 // a max-field-alignment constraint (#pragma pack). So calculate
1421 // the actual alignment of the field within the struct, and then
1422 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001423 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1424 const RecordDecl *Parent = Field->getParent();
1425 // We can only produce a sensible answer if the record is valid.
1426 if (!Parent->isInvalidDecl()) {
1427 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001428
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001429 // Start with the record's overall alignment.
1430 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001431
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001432 // Use the GCD of that and the offset within the record.
1433 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1434 if (Offset > 0) {
1435 // Alignment is always a power of 2, so the GCD will be a power of 2,
1436 // which means we get to do this crazy thing instead of Euclid's.
1437 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1438 if (LowBitOfOffset < FieldAlign)
1439 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1440 }
1441
1442 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001443 }
Charles Davis3fc51072010-02-23 04:52:00 +00001444 }
Chris Lattner68061312009-01-24 21:53:27 +00001445 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001446
Ken Dyckcc56c542011-01-15 18:38:59 +00001447 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001448}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001449
John McCallf1249922012-08-21 04:10:00 +00001450// getTypeInfoDataSizeInChars - Return the size of a type, in
1451// chars. If the type is a record, its data size is returned. This is
1452// the size of the memcpy that's performed when assigning this type
1453// using a trivial copy/move assignment operator.
1454std::pair<CharUnits, CharUnits>
1455ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1456 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1457
1458 // In C++, objects can sometimes be allocated into the tail padding
1459 // of a base-class subobject. We decide whether that's possible
1460 // during class layout, so here we can just trust the layout results.
1461 if (getLangOpts().CPlusPlus) {
1462 if (const RecordType *RT = T->getAs<RecordType>()) {
1463 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1464 sizeAndAlign.first = layout.getDataSize();
1465 }
1466 }
1467
1468 return sizeAndAlign;
1469}
1470
Richard Trieu04d2d942013-05-14 21:59:17 +00001471/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1472/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1473std::pair<CharUnits, CharUnits>
1474static getConstantArrayInfoInChars(const ASTContext &Context,
1475 const ConstantArrayType *CAT) {
1476 std::pair<CharUnits, CharUnits> EltInfo =
1477 Context.getTypeInfoInChars(CAT->getElementType());
1478 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001479 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1480 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001481 "Overflow in array type char size evaluation");
1482 uint64_t Width = EltInfo.first.getQuantity() * Size;
1483 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001484 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1485 Context.getTargetInfo().getPointerWidth(0) == 64)
1486 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001487 return std::make_pair(CharUnits::fromQuantity(Width),
1488 CharUnits::fromQuantity(Align));
1489}
1490
John McCall87fe5d52010-05-20 01:18:31 +00001491std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001492ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001493 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1494 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001495 TypeInfo Info = getTypeInfo(T);
1496 return std::make_pair(toCharUnitsFromBits(Info.Width),
1497 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001498}
1499
1500std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001501ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001502 return getTypeInfoInChars(T.getTypePtr());
1503}
1504
David Majnemer34b57492014-07-30 01:30:47 +00001505bool ASTContext::isAlignmentRequired(const Type *T) const {
1506 return getTypeInfo(T).AlignIsRequired;
1507}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001508
David Majnemer34b57492014-07-30 01:30:47 +00001509bool ASTContext::isAlignmentRequired(QualType T) const {
1510 return isAlignmentRequired(T.getTypePtr());
1511}
1512
1513TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001514 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1515 if (I != MemoizedTypeInfo.end())
1516 return I->second;
1517
1518 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1519 TypeInfo TI = getTypeInfoImpl(T);
1520 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001521 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001522}
1523
1524/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1525/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001526///
1527/// FIXME: Pointers into different addr spaces could have different sizes and
1528/// alignment requirements: getPointerInfo should take an AddrSpace, this
1529/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001530TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1531 uint64_t Width = 0;
1532 unsigned Align = 8;
1533 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001534 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001535#define TYPE(Class, Base)
1536#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001537#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001538#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001539#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1540 case Type::Class: \
1541 assert(!T->isDependentType() && "should not see dependent types here"); \
1542 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001543#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001544 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001545
Chris Lattner355332d2007-07-13 22:27:08 +00001546 case Type::FunctionNoProto:
1547 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001548 // GCC extension: alignof(function) = 32 bits
1549 Width = 0;
1550 Align = 32;
1551 break;
1552
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001553 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001554 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001555 Width = 0;
1556 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1557 break;
1558
Steve Naroff5c131802007-08-30 01:06:46 +00001559 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001560 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001561
David Majnemer34b57492014-07-30 01:30:47 +00001562 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001563 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001564 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001565 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001566 Width = EltInfo.Width * Size;
1567 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001568 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1569 getTargetInfo().getPointerWidth(0) == 64)
1570 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001571 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001572 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001573 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001574 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001575 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001576 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1577 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001578 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001579 // If the alignment is not a power of 2, round up to the next power of 2.
1580 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001581 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001582 Align = llvm::NextPowerOf2(Align);
1583 Width = llvm::RoundUpToAlignment(Width, Align);
1584 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001585 // Adjust the alignment based on the target max.
1586 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1587 if (TargetVectorAlign && TargetVectorAlign < Align)
1588 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001589 break;
1590 }
Chris Lattner647fb222007-07-18 18:26:58 +00001591
Chris Lattner7570e9c2008-03-08 08:52:55 +00001592 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001593 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001594 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001595 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001596 // GCC extension: alignof(void) = 8 bits.
1597 Width = 0;
1598 Align = 8;
1599 break;
1600
Chris Lattner6a4f7452007-12-19 19:23:28 +00001601 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001602 Width = Target->getBoolWidth();
1603 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001604 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001605 case BuiltinType::Char_S:
1606 case BuiltinType::Char_U:
1607 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001608 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001609 Width = Target->getCharWidth();
1610 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001611 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001612 case BuiltinType::WChar_S:
1613 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001614 Width = Target->getWCharWidth();
1615 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001616 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001617 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001618 Width = Target->getChar16Width();
1619 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001620 break;
1621 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001622 Width = Target->getChar32Width();
1623 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001624 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001625 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001626 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001627 Width = Target->getShortWidth();
1628 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001629 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001630 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001631 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001632 Width = Target->getIntWidth();
1633 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001634 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001635 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001636 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001637 Width = Target->getLongWidth();
1638 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001639 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001640 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001641 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001642 Width = Target->getLongLongWidth();
1643 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001644 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001645 case BuiltinType::Int128:
1646 case BuiltinType::UInt128:
1647 Width = 128;
1648 Align = 128; // int128_t is 128-bit aligned on all targets.
1649 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001650 case BuiltinType::Half:
1651 Width = Target->getHalfWidth();
1652 Align = Target->getHalfAlign();
1653 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001654 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001655 Width = Target->getFloatWidth();
1656 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001657 break;
1658 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001659 Width = Target->getDoubleWidth();
1660 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001661 break;
1662 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001663 Width = Target->getLongDoubleWidth();
1664 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001665 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001666 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001667 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1668 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001669 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001670 case BuiltinType::ObjCId:
1671 case BuiltinType::ObjCClass:
1672 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001673 Width = Target->getPointerWidth(0);
1674 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001675 break;
Guy Benyei61054192013-02-07 10:55:47 +00001676 case BuiltinType::OCLSampler:
1677 // Samplers are modeled as integers.
1678 Width = Target->getIntWidth();
1679 Align = Target->getIntAlign();
1680 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001681 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001682 case BuiltinType::OCLClkEvent:
1683 case BuiltinType::OCLQueue:
1684 case BuiltinType::OCLNDRange:
1685 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001686 case BuiltinType::OCLImage1d:
1687 case BuiltinType::OCLImage1dArray:
1688 case BuiltinType::OCLImage1dBuffer:
1689 case BuiltinType::OCLImage2d:
1690 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001691 case BuiltinType::OCLImage2dDepth:
1692 case BuiltinType::OCLImage2dArrayDepth:
1693 case BuiltinType::OCLImage2dMSAA:
1694 case BuiltinType::OCLImage2dArrayMSAA:
1695 case BuiltinType::OCLImage2dMSAADepth:
1696 case BuiltinType::OCLImage2dArrayMSAADepth:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001697 case BuiltinType::OCLImage3d:
1698 // Currently these types are pointers to opaque types.
1699 Width = Target->getPointerWidth(0);
1700 Align = Target->getPointerAlign(0);
1701 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001702 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001703 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001704 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001705 Width = Target->getPointerWidth(0);
1706 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001707 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001708 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001709 unsigned AS = getTargetAddressSpace(
1710 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001711 Width = Target->getPointerWidth(AS);
1712 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001713 break;
1714 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001715 case Type::LValueReference:
1716 case Type::RValueReference: {
1717 // alignof and sizeof should never enter this code path here, so we go
1718 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001719 unsigned AS = getTargetAddressSpace(
1720 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001721 Width = Target->getPointerWidth(AS);
1722 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001723 break;
1724 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001725 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001726 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001727 Width = Target->getPointerWidth(AS);
1728 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001729 break;
1730 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001731 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001732 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001733 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001734 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001735 }
Chris Lattner647fb222007-07-18 18:26:58 +00001736 case Type::Complex: {
1737 // Complex types have the same alignment as their elements, but twice the
1738 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001739 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1740 Width = EltInfo.Width * 2;
1741 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001742 break;
1743 }
John McCall8b07ec22010-05-15 11:32:37 +00001744 case Type::ObjCObject:
1745 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001746 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001747 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001748 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001749 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001750 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001751 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001752 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001753 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001754 break;
1755 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001756 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001757 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001758 const TagType *TT = cast<TagType>(T);
1759
1760 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001761 Width = 8;
1762 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001763 break;
1764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765
David Majnemer475b25e2015-01-21 10:54:38 +00001766 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1767 const EnumDecl *ED = ET->getDecl();
1768 TypeInfo Info =
1769 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1770 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1771 Info.Align = AttrAlign;
1772 Info.AlignIsRequired = true;
1773 }
1774 return Info;
1775 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001776
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001777 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001778 const RecordDecl *RD = RT->getDecl();
1779 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001780 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001781 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001782 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001783 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001784 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001785
Chris Lattner63d2b362009-10-22 05:17:15 +00001786 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001787 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1788 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001789
Richard Smith30482bc2011-02-20 03:19:35 +00001790 case Type::Auto: {
1791 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001792 assert(!A->getDeducedType().isNull() &&
1793 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001794 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001795 }
1796
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001797 case Type::Paren:
1798 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1799
Douglas Gregoref462e62009-04-30 17:32:17 +00001800 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001801 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001802 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001803 // If the typedef has an aligned attribute on it, it overrides any computed
1804 // alignment we have. This violates the GCC documentation (which says that
1805 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001806 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001807 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001808 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001809 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001810 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001811 AlignIsRequired = Info.AlignIsRequired;
1812 }
David Majnemer34b57492014-07-30 01:30:47 +00001813 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001814 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001815 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001816
Abramo Bagnara6150c882010-05-11 21:36:43 +00001817 case Type::Elaborated:
1818 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001819
John McCall81904512011-01-06 01:58:22 +00001820 case Type::Attributed:
1821 return getTypeInfo(
1822 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1823
Eli Friedman0dfb8892011-10-06 23:00:33 +00001824 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001825 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001826 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1827 Width = Info.Width;
1828 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001829
1830 // If the size of the type doesn't exceed the platform's max
1831 // atomic promotion width, make the size and alignment more
1832 // favorable to atomic operations:
1833 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1834 // Round the size up to a power of 2.
1835 if (!llvm::isPowerOf2_64(Width))
1836 Width = llvm::NextPowerOf2(Width);
1837
1838 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001839 Align = static_cast<unsigned>(Width);
1840 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001841 }
1842
Douglas Gregoref462e62009-04-30 17:32:17 +00001843 }
Mike Stump11289f42009-09-09 15:08:12 +00001844
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001845 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001846 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001847}
1848
Alexey Bataev00396512015-07-02 03:40:19 +00001849unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1850 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1851 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1852 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1853 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1854 getTargetInfo().getABI() == "elfv1-qpx" &&
1855 T->isSpecificBuiltinType(BuiltinType::Double))
1856 SimdAlign = 256;
1857 return SimdAlign;
1858}
1859
Ken Dyckcc56c542011-01-15 18:38:59 +00001860/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1861CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1862 return CharUnits::fromQuantity(BitSize / getCharWidth());
1863}
1864
Ken Dyckb0fcc592011-02-11 01:54:29 +00001865/// toBits - Convert a size in characters to a size in characters.
1866int64_t ASTContext::toBits(CharUnits CharSize) const {
1867 return CharSize.getQuantity() * getCharWidth();
1868}
1869
Ken Dyck8c89d592009-12-22 14:23:30 +00001870/// getTypeSizeInChars - Return the size of the specified type, in characters.
1871/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001872CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001873 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001874}
Jay Foad39c79802011-01-12 09:06:06 +00001875CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001876 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001877}
1878
Ken Dycka6046ab2010-01-26 17:25:18 +00001879/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001880/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001881CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001882 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001883}
Jay Foad39c79802011-01-12 09:06:06 +00001884CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001885 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001886}
1887
Chris Lattnera3402cd2009-01-27 18:08:34 +00001888/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1889/// type for the current target in bits. This can be different than the ABI
1890/// alignment in cases where it is beneficial for performance to overalign
1891/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001892unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001893 TypeInfo TI = getTypeInfo(T);
1894 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001895
David Majnemere1544562015-04-24 01:25:05 +00001896 T = T->getBaseElementTypeUnsafe();
1897
1898 // The preferred alignment of member pointers is that of a pointer.
1899 if (T->isMemberPointerType())
1900 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1901
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001902 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1903 return ABIAlign; // Never overalign on XCore.
1904
Eli Friedman7ab09572009-05-25 21:27:19 +00001905 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001906 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001907 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001908 if (const EnumType *ET = T->getAs<EnumType>())
1909 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001910 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001911 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1912 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001913 // Don't increase the alignment if an alignment attribute was specified on a
1914 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001915 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001916 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001917
Chris Lattnera3402cd2009-01-27 18:08:34 +00001918 return ABIAlign;
1919}
1920
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001921/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1922/// for __attribute__((aligned)) on this target, to be used if no alignment
1923/// value is specified.
1924unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1925 return getTargetInfo().getDefaultAlignForAttributeAligned();
1926}
1927
Ulrich Weigandfa806422013-05-06 16:23:57 +00001928/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1929/// to a global variable of the specified type.
1930unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1931 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1932}
1933
1934/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1935/// should be given to a global variable of the specified type.
1936CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1937 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1938}
1939
David Majnemer08ef2ba2015-06-23 20:34:18 +00001940CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1941 CharUnits Offset = CharUnits::Zero();
1942 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1943 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1944 Offset += Layout->getBaseClassOffset(Base);
1945 Layout = &getASTRecordLayout(Base);
1946 }
1947 return Offset;
1948}
1949
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001950/// DeepCollectObjCIvars -
1951/// This routine first collects all declared, but not synthesized, ivars in
1952/// super class and then collects all ivars, including those synthesized for
1953/// current class. This routine is used for implementation of current class
1954/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001955///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001956void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1957 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001958 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001959 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1960 DeepCollectObjCIvars(SuperClass, false, Ivars);
1961 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001962 for (const auto *I : OI->ivars())
1963 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001964 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001965 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001966 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001967 Iv= Iv->getNextIvar())
1968 Ivars.push_back(Iv);
1969 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001970}
1971
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001972/// CollectInheritedProtocols - Collect all protocols in current class and
1973/// those inherited by it.
1974void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001975 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001976 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001977 // We can use protocol_iterator here instead of
1978 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001979 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001980 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001981 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001982
1983 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001984 for (const auto *Cat : OI->visible_categories())
1985 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001986
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001987 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1988 while (SD) {
1989 CollectInheritedProtocols(SD, Protocols);
1990 SD = SD->getSuperClass();
1991 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001992 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001993 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001994 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001995 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001996 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001997 // Insert the protocol.
1998 if (!Protocols.insert(
1999 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2000 return;
2001
2002 for (auto *Proto : OP->protocols())
2003 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002004 }
2005}
2006
Jay Foad39c79802011-01-12 09:06:06 +00002007unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002008 unsigned count = 0;
2009 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002010 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002011 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002012
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002013 // Count ivar defined in this class's implementation. This
2014 // includes synthesized ivars.
2015 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002016 count += ImplDecl->ivar_size();
2017
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002018 return count;
2019}
2020
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002021bool ASTContext::isSentinelNullExpr(const Expr *E) {
2022 if (!E)
2023 return false;
2024
2025 // nullptr_t is always treated as null.
2026 if (E->getType()->isNullPtrType()) return true;
2027
2028 if (E->getType()->isAnyPointerType() &&
2029 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2030 Expr::NPC_ValueDependentIsNull))
2031 return true;
2032
2033 // Unfortunately, __null has type 'int'.
2034 if (isa<GNUNullExpr>(E)) return true;
2035
2036 return false;
2037}
2038
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002039/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2040ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2041 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2042 I = ObjCImpls.find(D);
2043 if (I != ObjCImpls.end())
2044 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002045 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002046}
2047/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2048ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2049 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2050 I = ObjCImpls.find(D);
2051 if (I != ObjCImpls.end())
2052 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002053 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002054}
2055
2056/// \brief Set the implementation of ObjCInterfaceDecl.
2057void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2058 ObjCImplementationDecl *ImplD) {
2059 assert(IFaceD && ImplD && "Passed null params");
2060 ObjCImpls[IFaceD] = ImplD;
2061}
2062/// \brief Set the implementation of ObjCCategoryDecl.
2063void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2064 ObjCCategoryImplDecl *ImplD) {
2065 assert(CatD && ImplD && "Passed null params");
2066 ObjCImpls[CatD] = ImplD;
2067}
2068
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002069const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2070 const NamedDecl *ND) const {
2071 if (const ObjCInterfaceDecl *ID =
2072 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002073 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002074 if (const ObjCCategoryDecl *CD =
2075 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002076 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002077 if (const ObjCImplDecl *IMD =
2078 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002079 return IMD->getClassInterface();
2080
Craig Topper36250ad2014-05-12 05:36:57 +00002081 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002082}
2083
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002084/// \brief Get the copy initialization expression of VarDecl,or NULL if
2085/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002086Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002087 assert(VD && "Passed null params");
2088 assert(VD->hasAttr<BlocksAttr>() &&
2089 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002090 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002091 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002092 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002093}
2094
2095/// \brief Set the copy inialization expression of a block var decl.
2096void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2097 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002098 assert(VD->hasAttr<BlocksAttr>() &&
2099 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002100 BlockVarCopyInits[VD] = Init;
2101}
2102
John McCallbcd03502009-12-07 02:54:59 +00002103TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002104 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002105 if (!DataSize)
2106 DataSize = TypeLoc::getFullDataSizeForType(T);
2107 else
2108 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002109 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002110
John McCallbcd03502009-12-07 02:54:59 +00002111 TypeSourceInfo *TInfo =
2112 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2113 new (TInfo) TypeSourceInfo(T);
2114 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002115}
2116
John McCallbcd03502009-12-07 02:54:59 +00002117TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002118 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002119 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002120 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002121 return DI;
2122}
2123
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002124const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002125ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002126 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002127}
2128
2129const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002130ASTContext::getASTObjCImplementationLayout(
2131 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002132 return getObjCLayout(D->getClassInterface(), D);
2133}
2134
Chris Lattner983a8bb2007-07-13 22:13:22 +00002135//===----------------------------------------------------------------------===//
2136// Type creation/memoization methods
2137//===----------------------------------------------------------------------===//
2138
Jay Foad39c79802011-01-12 09:06:06 +00002139QualType
John McCall33ddac02011-01-19 10:06:00 +00002140ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2141 unsigned fastQuals = quals.getFastQualifiers();
2142 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002143
2144 // Check if we've already instantiated this type.
2145 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002146 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002147 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002148 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2149 assert(eq->getQualifiers() == quals);
2150 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002151 }
2152
John McCall33ddac02011-01-19 10:06:00 +00002153 // If the base type is not canonical, make the appropriate canonical type.
2154 QualType canon;
2155 if (!baseType->isCanonicalUnqualified()) {
2156 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002157 canonSplit.Quals.addConsistentQualifiers(quals);
2158 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002159
2160 // Re-find the insert position.
2161 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2162 }
2163
2164 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2165 ExtQualNodes.InsertNode(eq, insertPos);
2166 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002167}
2168
Jay Foad39c79802011-01-12 09:06:06 +00002169QualType
2170ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002171 QualType CanT = getCanonicalType(T);
2172 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002173 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002174
John McCall8ccfcb52009-09-24 19:53:00 +00002175 // If we are composing extended qualifiers together, merge together
2176 // into one ExtQuals node.
2177 QualifierCollector Quals;
2178 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002179
John McCall8ccfcb52009-09-24 19:53:00 +00002180 // If this type already has an address space specified, it cannot get
2181 // another one.
2182 assert(!Quals.hasAddressSpace() &&
2183 "Type cannot be in multiple addr spaces!");
2184 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002185
John McCall8ccfcb52009-09-24 19:53:00 +00002186 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002187}
2188
Chris Lattnerd60183d2009-02-18 22:53:11 +00002189QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002190 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002191 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002192 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002193 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002194
John McCall53fa7142010-12-24 02:08:15 +00002195 if (const PointerType *ptr = T->getAs<PointerType>()) {
2196 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002197 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002198 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2199 return getPointerType(ResultType);
2200 }
2201 }
Mike Stump11289f42009-09-09 15:08:12 +00002202
John McCall8ccfcb52009-09-24 19:53:00 +00002203 // If we are composing extended qualifiers together, merge together
2204 // into one ExtQuals node.
2205 QualifierCollector Quals;
2206 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002207
John McCall8ccfcb52009-09-24 19:53:00 +00002208 // If this type already has an ObjCGC specified, it cannot get
2209 // another one.
2210 assert(!Quals.hasObjCGCAttr() &&
2211 "Type cannot have multiple ObjCGCs!");
2212 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002213
John McCall8ccfcb52009-09-24 19:53:00 +00002214 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002215}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002216
John McCall4f5019e2010-12-19 02:44:49 +00002217const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2218 FunctionType::ExtInfo Info) {
2219 if (T->getExtInfo() == Info)
2220 return T;
2221
2222 QualType Result;
2223 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002224 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002225 } else {
2226 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2227 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2228 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002229 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002230 }
2231
2232 return cast<FunctionType>(Result.getTypePtr());
2233}
2234
Richard Smith2a7d4812013-05-04 07:00:32 +00002235void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2236 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002237 FD = FD->getMostRecentDecl();
2238 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002239 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2240 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002241 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002242 if (FunctionDecl *Next = FD->getPreviousDecl())
2243 FD = Next;
2244 else
2245 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002246 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002247 if (ASTMutationListener *L = getASTMutationListener())
2248 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002249}
2250
Richard Smith0b3a4622014-11-13 20:01:57 +00002251/// Get a function type and produce the equivalent function type with the
2252/// specified exception specification. Type sugar that can be present on a
2253/// declaration of a function with an exception specification is permitted
2254/// and preserved. Other type sugar (for instance, typedefs) is not.
2255static QualType getFunctionTypeWithExceptionSpec(
2256 ASTContext &Context, QualType Orig,
2257 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2258 // Might have some parens.
2259 if (auto *PT = dyn_cast<ParenType>(Orig))
2260 return Context.getParenType(
2261 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2262
2263 // Might have a calling-convention attribute.
2264 if (auto *AT = dyn_cast<AttributedType>(Orig))
2265 return Context.getAttributedType(
2266 AT->getAttrKind(),
2267 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2268 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2269 ESI));
2270
2271 // Anything else must be a function type. Rebuild it with the new exception
2272 // specification.
2273 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2274 return Context.getFunctionType(
2275 Proto->getReturnType(), Proto->getParamTypes(),
2276 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2277}
2278
2279void ASTContext::adjustExceptionSpec(
2280 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2281 bool AsWritten) {
2282 // Update the type.
2283 QualType Updated =
2284 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2285 FD->setType(Updated);
2286
2287 if (!AsWritten)
2288 return;
2289
2290 // Update the type in the type source information too.
2291 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2292 // If the type and the type-as-written differ, we may need to update
2293 // the type-as-written too.
2294 if (TSInfo->getType() != FD->getType())
2295 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2296
2297 // FIXME: When we get proper type location information for exceptions,
2298 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2299 // up the TypeSourceInfo;
2300 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2301 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2302 "TypeLoc size mismatch from updating exception specification");
2303 TSInfo->overrideType(Updated);
2304 }
2305}
2306
Chris Lattnerc6395932007-06-22 20:56:16 +00002307/// getComplexType - Return the uniqued reference to the type for a complex
2308/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002309QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002310 // Unique pointers, to guarantee there is only one pointer of a particular
2311 // structure.
2312 llvm::FoldingSetNodeID ID;
2313 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002314
Craig Topper36250ad2014-05-12 05:36:57 +00002315 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002316 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2317 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002318
Chris Lattnerc6395932007-06-22 20:56:16 +00002319 // If the pointee type isn't canonical, this won't be a canonical type either,
2320 // so fill in the canonical type field.
2321 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002322 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002323 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002324
Chris Lattnerc6395932007-06-22 20:56:16 +00002325 // Get the new insert position for the node we care about.
2326 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002327 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002328 }
John McCall90d1c2d2009-09-24 23:30:46 +00002329 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002330 Types.push_back(New);
2331 ComplexTypes.InsertNode(New, InsertPos);
2332 return QualType(New, 0);
2333}
2334
Chris Lattner970e54e2006-11-12 00:37:36 +00002335/// getPointerType - Return the uniqued reference to the type for a pointer to
2336/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002337QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002338 // Unique pointers, to guarantee there is only one pointer of a particular
2339 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002340 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002341 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002342
Craig Topper36250ad2014-05-12 05:36:57 +00002343 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002344 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002345 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002346
Chris Lattner7ccecb92006-11-12 08:50:50 +00002347 // If the pointee type isn't canonical, this won't be a canonical type either,
2348 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002349 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002350 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002351 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002352
Bob Wilsonc8541f22013-03-15 17:12:43 +00002353 // Get the new insert position for the node we care about.
2354 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002355 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002356 }
John McCall90d1c2d2009-09-24 23:30:46 +00002357 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002358 Types.push_back(New);
2359 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002360 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002361}
2362
Reid Kleckner0503a872013-12-05 01:23:43 +00002363QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2364 llvm::FoldingSetNodeID ID;
2365 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002366 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002367 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2368 if (AT)
2369 return QualType(AT, 0);
2370
2371 QualType Canonical = getCanonicalType(New);
2372
2373 // Get the new insert position for the node we care about.
2374 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002375 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002376
2377 AT = new (*this, TypeAlignment)
2378 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2379 Types.push_back(AT);
2380 AdjustedTypes.InsertNode(AT, InsertPos);
2381 return QualType(AT, 0);
2382}
2383
Reid Kleckner8a365022013-06-24 17:51:48 +00002384QualType ASTContext::getDecayedType(QualType T) const {
2385 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2386
Reid Kleckner8a365022013-06-24 17:51:48 +00002387 QualType Decayed;
2388
2389 // C99 6.7.5.3p7:
2390 // A declaration of a parameter as "array of type" shall be
2391 // adjusted to "qualified pointer to type", where the type
2392 // qualifiers (if any) are those specified within the [ and ] of
2393 // the array type derivation.
2394 if (T->isArrayType())
2395 Decayed = getArrayDecayedType(T);
2396
2397 // C99 6.7.5.3p8:
2398 // A declaration of a parameter as "function returning type"
2399 // shall be adjusted to "pointer to function returning type", as
2400 // in 6.3.2.1.
2401 if (T->isFunctionType())
2402 Decayed = getPointerType(T);
2403
Reid Kleckner0503a872013-12-05 01:23:43 +00002404 llvm::FoldingSetNodeID ID;
2405 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002406 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002407 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2408 if (AT)
2409 return QualType(AT, 0);
2410
Reid Kleckner8a365022013-06-24 17:51:48 +00002411 QualType Canonical = getCanonicalType(Decayed);
2412
2413 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002414 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002415 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002416
Reid Kleckner0503a872013-12-05 01:23:43 +00002417 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2418 Types.push_back(AT);
2419 AdjustedTypes.InsertNode(AT, InsertPos);
2420 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002421}
2422
Mike Stump11289f42009-09-09 15:08:12 +00002423/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002424/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002425QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002426 assert(T->isFunctionType() && "block of function types only");
2427 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002428 // structure.
2429 llvm::FoldingSetNodeID ID;
2430 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002431
Craig Topper36250ad2014-05-12 05:36:57 +00002432 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002433 if (BlockPointerType *PT =
2434 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2435 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002436
2437 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002438 // type either so fill in the canonical type field.
2439 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002440 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002441 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002442
Steve Naroffec33ed92008-08-27 16:04:49 +00002443 // Get the new insert position for the node we care about.
2444 BlockPointerType *NewIP =
2445 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002446 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002447 }
John McCall90d1c2d2009-09-24 23:30:46 +00002448 BlockPointerType *New
2449 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002450 Types.push_back(New);
2451 BlockPointerTypes.InsertNode(New, InsertPos);
2452 return QualType(New, 0);
2453}
2454
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002455/// getLValueReferenceType - Return the uniqued reference to the type for an
2456/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002457QualType
2458ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002459 assert(getCanonicalType(T) != OverloadTy &&
2460 "Unresolved overloaded function type");
2461
Bill Wendling3708c182007-05-27 10:15:43 +00002462 // Unique pointers, to guarantee there is only one pointer of a particular
2463 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002464 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002465 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002466
Craig Topper36250ad2014-05-12 05:36:57 +00002467 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002468 if (LValueReferenceType *RT =
2469 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002470 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002471
John McCallfc93cf92009-10-22 22:37:11 +00002472 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2473
Bill Wendling3708c182007-05-27 10:15:43 +00002474 // If the referencee type isn't canonical, this won't be a canonical type
2475 // either, so fill in the canonical type field.
2476 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002477 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2478 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2479 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002480
Bill Wendling3708c182007-05-27 10:15:43 +00002481 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002482 LValueReferenceType *NewIP =
2483 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002484 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002485 }
2486
John McCall90d1c2d2009-09-24 23:30:46 +00002487 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002488 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2489 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002490 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002491 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002492
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002493 return QualType(New, 0);
2494}
2495
2496/// getRValueReferenceType - Return the uniqued reference to the type for an
2497/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002498QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002499 // Unique pointers, to guarantee there is only one pointer of a particular
2500 // structure.
2501 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002502 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002503
Craig Topper36250ad2014-05-12 05:36:57 +00002504 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002505 if (RValueReferenceType *RT =
2506 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2507 return QualType(RT, 0);
2508
John McCallfc93cf92009-10-22 22:37:11 +00002509 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2510
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002511 // If the referencee type isn't canonical, this won't be a canonical type
2512 // either, so fill in the canonical type field.
2513 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002514 if (InnerRef || !T.isCanonical()) {
2515 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2516 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002517
2518 // Get the new insert position for the node we care about.
2519 RValueReferenceType *NewIP =
2520 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002521 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002522 }
2523
John McCall90d1c2d2009-09-24 23:30:46 +00002524 RValueReferenceType *New
2525 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002526 Types.push_back(New);
2527 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002528 return QualType(New, 0);
2529}
2530
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002531/// getMemberPointerType - Return the uniqued reference to the type for a
2532/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002533QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002534 // Unique pointers, to guarantee there is only one pointer of a particular
2535 // structure.
2536 llvm::FoldingSetNodeID ID;
2537 MemberPointerType::Profile(ID, T, Cls);
2538
Craig Topper36250ad2014-05-12 05:36:57 +00002539 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002540 if (MemberPointerType *PT =
2541 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2542 return QualType(PT, 0);
2543
2544 // If the pointee or class type isn't canonical, this won't be a canonical
2545 // type either, so fill in the canonical type field.
2546 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002547 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002548 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2549
2550 // Get the new insert position for the node we care about.
2551 MemberPointerType *NewIP =
2552 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002553 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002554 }
John McCall90d1c2d2009-09-24 23:30:46 +00002555 MemberPointerType *New
2556 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002557 Types.push_back(New);
2558 MemberPointerTypes.InsertNode(New, InsertPos);
2559 return QualType(New, 0);
2560}
2561
Mike Stump11289f42009-09-09 15:08:12 +00002562/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002563/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002564QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002565 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002566 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002567 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002568 assert((EltTy->isDependentType() ||
2569 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002570 "Constant array of VLAs is illegal!");
2571
Chris Lattnere2df3f92009-05-13 04:12:56 +00002572 // Convert the array size into a canonical width matching the pointer size for
2573 // the target.
2574 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002575 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002576 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002577
Chris Lattner23b7eb62007-06-15 23:05:46 +00002578 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002579 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002580
Craig Topper36250ad2014-05-12 05:36:57 +00002581 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002582 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002583 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002584 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002585
John McCall33ddac02011-01-19 10:06:00 +00002586 // If the element type isn't canonical or has qualifiers, this won't
2587 // be a canonical type either, so fill in the canonical type field.
2588 QualType Canon;
2589 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2590 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002591 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002592 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002593 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002594
Chris Lattner36f8e652007-01-27 08:31:04 +00002595 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002596 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002597 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002598 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002599 }
Mike Stump11289f42009-09-09 15:08:12 +00002600
John McCall90d1c2d2009-09-24 23:30:46 +00002601 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002602 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002603 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002604 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002605 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002606}
2607
John McCall06549462011-01-18 08:40:38 +00002608/// getVariableArrayDecayedType - Turns the given type, which may be
2609/// variably-modified, into the corresponding type with all the known
2610/// sizes replaced with [*].
2611QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2612 // Vastly most common case.
2613 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002614
John McCall06549462011-01-18 08:40:38 +00002615 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002616
John McCall06549462011-01-18 08:40:38 +00002617 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002618 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002619 switch (ty->getTypeClass()) {
2620#define TYPE(Class, Base)
2621#define ABSTRACT_TYPE(Class, Base)
2622#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2623#include "clang/AST/TypeNodes.def"
2624 llvm_unreachable("didn't desugar past all non-canonical types?");
2625
2626 // These types should never be variably-modified.
2627 case Type::Builtin:
2628 case Type::Complex:
2629 case Type::Vector:
2630 case Type::ExtVector:
2631 case Type::DependentSizedExtVector:
2632 case Type::ObjCObject:
2633 case Type::ObjCInterface:
2634 case Type::ObjCObjectPointer:
2635 case Type::Record:
2636 case Type::Enum:
2637 case Type::UnresolvedUsing:
2638 case Type::TypeOfExpr:
2639 case Type::TypeOf:
2640 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002641 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002642 case Type::DependentName:
2643 case Type::InjectedClassName:
2644 case Type::TemplateSpecialization:
2645 case Type::DependentTemplateSpecialization:
2646 case Type::TemplateTypeParm:
2647 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002648 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002649 case Type::PackExpansion:
2650 llvm_unreachable("type should never be variably-modified");
2651
2652 // These types can be variably-modified but should never need to
2653 // further decay.
2654 case Type::FunctionNoProto:
2655 case Type::FunctionProto:
2656 case Type::BlockPointer:
2657 case Type::MemberPointer:
2658 return type;
2659
2660 // These types can be variably-modified. All these modifications
2661 // preserve structure except as noted by comments.
2662 // TODO: if we ever care about optimizing VLAs, there are no-op
2663 // optimizations available here.
2664 case Type::Pointer:
2665 result = getPointerType(getVariableArrayDecayedType(
2666 cast<PointerType>(ty)->getPointeeType()));
2667 break;
2668
2669 case Type::LValueReference: {
2670 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2671 result = getLValueReferenceType(
2672 getVariableArrayDecayedType(lv->getPointeeType()),
2673 lv->isSpelledAsLValue());
2674 break;
2675 }
2676
2677 case Type::RValueReference: {
2678 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2679 result = getRValueReferenceType(
2680 getVariableArrayDecayedType(lv->getPointeeType()));
2681 break;
2682 }
2683
Eli Friedman0dfb8892011-10-06 23:00:33 +00002684 case Type::Atomic: {
2685 const AtomicType *at = cast<AtomicType>(ty);
2686 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2687 break;
2688 }
2689
John McCall06549462011-01-18 08:40:38 +00002690 case Type::ConstantArray: {
2691 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2692 result = getConstantArrayType(
2693 getVariableArrayDecayedType(cat->getElementType()),
2694 cat->getSize(),
2695 cat->getSizeModifier(),
2696 cat->getIndexTypeCVRQualifiers());
2697 break;
2698 }
2699
2700 case Type::DependentSizedArray: {
2701 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2702 result = getDependentSizedArrayType(
2703 getVariableArrayDecayedType(dat->getElementType()),
2704 dat->getSizeExpr(),
2705 dat->getSizeModifier(),
2706 dat->getIndexTypeCVRQualifiers(),
2707 dat->getBracketsRange());
2708 break;
2709 }
2710
2711 // Turn incomplete types into [*] types.
2712 case Type::IncompleteArray: {
2713 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2714 result = getVariableArrayType(
2715 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002716 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002717 ArrayType::Normal,
2718 iat->getIndexTypeCVRQualifiers(),
2719 SourceRange());
2720 break;
2721 }
2722
2723 // Turn VLA types into [*] types.
2724 case Type::VariableArray: {
2725 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2726 result = getVariableArrayType(
2727 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002728 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002729 ArrayType::Star,
2730 vat->getIndexTypeCVRQualifiers(),
2731 vat->getBracketsRange());
2732 break;
2733 }
2734 }
2735
2736 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002737 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002738}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002739
Steve Naroffcadebd02007-08-30 18:14:25 +00002740/// getVariableArrayType - Returns a non-unique reference to the type for a
2741/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002742QualType ASTContext::getVariableArrayType(QualType EltTy,
2743 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002744 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002745 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002746 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002747 // Since we don't unique expressions, it isn't possible to unique VLA's
2748 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002749 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002750
John McCall33ddac02011-01-19 10:06:00 +00002751 // Be sure to pull qualifiers off the element type.
2752 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2753 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002754 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002755 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002756 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002757 }
2758
John McCall90d1c2d2009-09-24 23:30:46 +00002759 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002760 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002761
2762 VariableArrayTypes.push_back(New);
2763 Types.push_back(New);
2764 return QualType(New, 0);
2765}
2766
Douglas Gregor4619e432008-12-05 23:32:09 +00002767/// getDependentSizedArrayType - Returns a non-unique reference to
2768/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002769/// type.
John McCall33ddac02011-01-19 10:06:00 +00002770QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2771 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002772 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002773 unsigned elementTypeQuals,
2774 SourceRange brackets) const {
2775 assert((!numElements || numElements->isTypeDependent() ||
2776 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002777 "Size must be type- or value-dependent!");
2778
John McCall33ddac02011-01-19 10:06:00 +00002779 // Dependently-sized array types that do not have a specified number
2780 // of elements will have their sizes deduced from a dependent
2781 // initializer. We do no canonicalization here at all, which is okay
2782 // because they can't be used in most locations.
2783 if (!numElements) {
2784 DependentSizedArrayType *newType
2785 = new (*this, TypeAlignment)
2786 DependentSizedArrayType(*this, elementType, QualType(),
2787 numElements, ASM, elementTypeQuals,
2788 brackets);
2789 Types.push_back(newType);
2790 return QualType(newType, 0);
2791 }
2792
2793 // Otherwise, we actually build a new type every time, but we
2794 // also build a canonical type.
2795
2796 SplitQualType canonElementType = getCanonicalType(elementType).split();
2797
Craig Topper36250ad2014-05-12 05:36:57 +00002798 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002799 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002800 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002801 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002802 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002803
John McCall33ddac02011-01-19 10:06:00 +00002804 // Look for an existing type with these properties.
2805 DependentSizedArrayType *canonTy =
2806 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002807
John McCall33ddac02011-01-19 10:06:00 +00002808 // If we don't have one, build one.
2809 if (!canonTy) {
2810 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002811 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002812 QualType(), numElements, ASM, elementTypeQuals,
2813 brackets);
2814 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2815 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002816 }
2817
John McCall33ddac02011-01-19 10:06:00 +00002818 // Apply qualifiers from the element type to the array.
2819 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002820 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002821
David Majnemer16a74702015-07-24 05:54:19 +00002822 // If we didn't need extra canonicalization for the element type or the size
2823 // expression, then just use that as our result.
2824 if (QualType(canonElementType.Ty, 0) == elementType &&
2825 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002826 return canon;
2827
2828 // Otherwise, we need to build a type which follows the spelling
2829 // of the element type.
2830 DependentSizedArrayType *sugaredType
2831 = new (*this, TypeAlignment)
2832 DependentSizedArrayType(*this, elementType, canon, numElements,
2833 ASM, elementTypeQuals, brackets);
2834 Types.push_back(sugaredType);
2835 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002836}
2837
John McCall33ddac02011-01-19 10:06:00 +00002838QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002839 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002840 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002841 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002842 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002843
Craig Topper36250ad2014-05-12 05:36:57 +00002844 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002845 if (IncompleteArrayType *iat =
2846 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2847 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002848
2849 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002850 // either, so fill in the canonical type field. We also have to pull
2851 // qualifiers off the element type.
2852 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002853
John McCall33ddac02011-01-19 10:06:00 +00002854 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2855 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002856 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002857 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002858 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002859
2860 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002861 IncompleteArrayType *existing =
2862 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2863 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002864 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002865
John McCall33ddac02011-01-19 10:06:00 +00002866 IncompleteArrayType *newType = new (*this, TypeAlignment)
2867 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002868
John McCall33ddac02011-01-19 10:06:00 +00002869 IncompleteArrayTypes.InsertNode(newType, insertPos);
2870 Types.push_back(newType);
2871 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002872}
2873
Steve Naroff91fcddb2007-07-18 18:00:27 +00002874/// getVectorType - Return the unique reference to a vector type of
2875/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002876QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002877 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002878 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002879
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002880 // Check if we've already instantiated a vector of this type.
2881 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002882 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002883
Craig Topper36250ad2014-05-12 05:36:57 +00002884 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002885 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2886 return QualType(VTP, 0);
2887
2888 // If the element type isn't canonical, this won't be a canonical type either,
2889 // so fill in the canonical type field.
2890 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002891 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002892 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002893
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002894 // Get the new insert position for the node we care about.
2895 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002896 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002897 }
John McCall90d1c2d2009-09-24 23:30:46 +00002898 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002899 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002900 VectorTypes.InsertNode(New, InsertPos);
2901 Types.push_back(New);
2902 return QualType(New, 0);
2903}
2904
Nate Begemance4d7fc2008-04-18 23:10:10 +00002905/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002906/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002907QualType
2908ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002909 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002910
Steve Naroff91fcddb2007-07-18 18:00:27 +00002911 // Check if we've already instantiated a vector of this type.
2912 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002913 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002914 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002915 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002916 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2917 return QualType(VTP, 0);
2918
2919 // If the element type isn't canonical, this won't be a canonical type either,
2920 // so fill in the canonical type field.
2921 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002922 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002923 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002924
Steve Naroff91fcddb2007-07-18 18:00:27 +00002925 // Get the new insert position for the node we care about.
2926 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002927 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002928 }
John McCall90d1c2d2009-09-24 23:30:46 +00002929 ExtVectorType *New = new (*this, TypeAlignment)
2930 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002931 VectorTypes.InsertNode(New, InsertPos);
2932 Types.push_back(New);
2933 return QualType(New, 0);
2934}
2935
Jay Foad39c79802011-01-12 09:06:06 +00002936QualType
2937ASTContext::getDependentSizedExtVectorType(QualType vecType,
2938 Expr *SizeExpr,
2939 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002940 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002941 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002942 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002943
Craig Topper36250ad2014-05-12 05:36:57 +00002944 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002945 DependentSizedExtVectorType *Canon
2946 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2947 DependentSizedExtVectorType *New;
2948 if (Canon) {
2949 // We already have a canonical version of this array type; use it as
2950 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002951 New = new (*this, TypeAlignment)
2952 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2953 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002954 } else {
2955 QualType CanonVecTy = getCanonicalType(vecType);
2956 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002957 New = new (*this, TypeAlignment)
2958 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2959 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002960
2961 DependentSizedExtVectorType *CanonCheck
2962 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2963 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2964 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002965 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2966 } else {
2967 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2968 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002969 New = new (*this, TypeAlignment)
2970 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002971 }
2972 }
Mike Stump11289f42009-09-09 15:08:12 +00002973
Douglas Gregor758a8692009-06-17 21:51:59 +00002974 Types.push_back(New);
2975 return QualType(New, 0);
2976}
2977
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002978/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002979///
Jay Foad39c79802011-01-12 09:06:06 +00002980QualType
2981ASTContext::getFunctionNoProtoType(QualType ResultTy,
2982 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002983 const CallingConv CallConv = Info.getCC();
2984
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002985 // Unique functions, to guarantee there is only one function of a particular
2986 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002987 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002988 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002989
Craig Topper36250ad2014-05-12 05:36:57 +00002990 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002991 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002992 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002993 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002994
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002995 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002996 if (!ResultTy.isCanonical()) {
2997 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002998
Chris Lattner47955de2007-01-27 08:37:20 +00002999 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003000 FunctionNoProtoType *NewIP =
3001 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003002 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003003 }
Mike Stump11289f42009-09-09 15:08:12 +00003004
Roman Divacky65b88cd2011-03-01 17:40:53 +00003005 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00003006 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00003007 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00003008 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003009 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003010 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003011}
3012
Douglas Gregorcd780372013-01-17 23:36:45 +00003013/// \brief Determine whether \p T is canonical as the result type of a function.
3014static bool isCanonicalResultType(QualType T) {
3015 return T.isCanonical() &&
3016 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3017 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3018}
3019
Douglas Gregora602a152015-10-01 20:20:47 +00003020CanQualType
3021ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3022 CanQualType CanResultType = getCanonicalType(ResultType);
3023
3024 // Canonical result types do not have ARC lifetime qualifiers.
3025 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3026 Qualifiers Qs = CanResultType.getQualifiers();
3027 Qs.removeObjCLifetime();
3028 return CanQualType::CreateUnsafe(
3029 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3030 }
3031
3032 return CanResultType;
3033}
3034
Jay Foad39c79802011-01-12 09:06:06 +00003035QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003036ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003037 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003038 size_t NumArgs = ArgArray.size();
3039
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003040 // Unique functions, to guarantee there is only one function of a particular
3041 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003042 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003043 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3044 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003045
Craig Topper36250ad2014-05-12 05:36:57 +00003046 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003047 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003048 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003049 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003050
3051 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003052 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003053 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003054 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003055 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003056 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003057 isCanonical = false;
3058
3059 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003060 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003061 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003062 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003063 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003064 CanonicalArgs.reserve(NumArgs);
3065 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003066 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003067
John McCalldb40c7f2010-12-14 08:05:40 +00003068 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003069 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003070 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003071
Douglas Gregora602a152015-10-01 20:20:47 +00003072 // Adjust the canonical function result type.
3073 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003074 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003075
Chris Lattnerfd4de792007-01-27 01:15:32 +00003076 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003077 FunctionProtoType *NewIP =
3078 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003079 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003080 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003081
John McCall31168b02011-06-15 23:02:42 +00003082 // FunctionProtoType objects are allocated with extra bytes after
3083 // them for three variable size arrays at the end:
3084 // - parameter types
3085 // - exception types
3086 // - consumed-arguments flags
3087 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003088 // expression, or information used to resolve the exception
3089 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003090 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003091 NumArgs * sizeof(QualType);
Richard Smith8acb4282014-07-31 21:57:55 +00003092 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3093 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3094 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003095 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003096 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003097 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003098 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003099 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003100 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003101 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00003102 Size += NumArgs * sizeof(bool);
3103
John McCalldb40c7f2010-12-14 08:05:40 +00003104 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003105 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003106 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003107 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003108 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003109 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003110}
Chris Lattneref51c202006-11-10 07:17:23 +00003111
John McCalle78aac42010-03-10 03:28:59 +00003112#ifndef NDEBUG
3113static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3114 if (!isa<CXXRecordDecl>(D)) return false;
3115 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3116 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3117 return true;
3118 if (RD->getDescribedClassTemplate() &&
3119 !isa<ClassTemplateSpecializationDecl>(RD))
3120 return true;
3121 return false;
3122}
3123#endif
3124
3125/// getInjectedClassNameType - Return the unique reference to the
3126/// injected class name type for the specified templated declaration.
3127QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003128 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003129 assert(NeedsInjectedClassNameType(Decl));
3130 if (Decl->TypeForDecl) {
3131 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003132 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003133 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3134 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3135 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3136 } else {
John McCall424cec92011-01-19 06:33:43 +00003137 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003138 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003139 Decl->TypeForDecl = newType;
3140 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003141 }
3142 return QualType(Decl->TypeForDecl, 0);
3143}
3144
Douglas Gregor83a586e2008-04-13 21:07:44 +00003145/// getTypeDeclType - Return the unique reference to the type for the
3146/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003147QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003148 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003149 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003150
Richard Smithdda56e42011-04-15 14:24:37 +00003151 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003152 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003153
John McCall96f0b5f2010-03-10 06:48:02 +00003154 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3155 "Template type parameter types are always available.");
3156
John McCall81e38502010-02-16 03:57:14 +00003157 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003158 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003159 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003160 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003161 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003162 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003163 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003164 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003165 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003166 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3167 Decl->TypeForDecl = newType;
3168 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003169 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003170 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003171
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003172 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003173}
3174
Chris Lattner32d920b2007-01-26 02:01:53 +00003175/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003176/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003177QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003178ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3179 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003180 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003181
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003182 if (Canonical.isNull())
3183 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003184 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003185 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003186 Decl->TypeForDecl = newType;
3187 Types.push_back(newType);
3188 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003189}
3190
Jay Foad39c79802011-01-12 09:06:06 +00003191QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003192 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3193
Douglas Gregorec9fd132012-01-14 16:38:05 +00003194 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003195 if (PrevDecl->TypeForDecl)
3196 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3197
John McCall424cec92011-01-19 06:33:43 +00003198 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3199 Decl->TypeForDecl = newType;
3200 Types.push_back(newType);
3201 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003202}
3203
Jay Foad39c79802011-01-12 09:06:06 +00003204QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003205 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3206
Douglas Gregorec9fd132012-01-14 16:38:05 +00003207 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003208 if (PrevDecl->TypeForDecl)
3209 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3210
John McCall424cec92011-01-19 06:33:43 +00003211 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3212 Decl->TypeForDecl = newType;
3213 Types.push_back(newType);
3214 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003215}
3216
John McCall81904512011-01-06 01:58:22 +00003217QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3218 QualType modifiedType,
3219 QualType equivalentType) {
3220 llvm::FoldingSetNodeID id;
3221 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3222
Craig Topper36250ad2014-05-12 05:36:57 +00003223 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003224 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3225 if (type) return QualType(type, 0);
3226
3227 QualType canon = getCanonicalType(equivalentType);
3228 type = new (*this, TypeAlignment)
3229 AttributedType(canon, attrKind, modifiedType, equivalentType);
3230
3231 Types.push_back(type);
3232 AttributedTypes.InsertNode(type, insertPos);
3233
3234 return QualType(type, 0);
3235}
3236
3237
John McCallcebee162009-10-18 09:09:24 +00003238/// \brief Retrieve a substitution-result type.
3239QualType
3240ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003241 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003242 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003243 && "replacement types must always be canonical");
3244
3245 llvm::FoldingSetNodeID ID;
3246 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003247 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003248 SubstTemplateTypeParmType *SubstParm
3249 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3250
3251 if (!SubstParm) {
3252 SubstParm = new (*this, TypeAlignment)
3253 SubstTemplateTypeParmType(Parm, Replacement);
3254 Types.push_back(SubstParm);
3255 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3256 }
3257
3258 return QualType(SubstParm, 0);
3259}
3260
Douglas Gregorada4b792011-01-14 02:55:32 +00003261/// \brief Retrieve a
3262QualType ASTContext::getSubstTemplateTypeParmPackType(
3263 const TemplateTypeParmType *Parm,
3264 const TemplateArgument &ArgPack) {
3265#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003266 for (const auto &P : ArgPack.pack_elements()) {
3267 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3268 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003269 }
3270#endif
3271
3272 llvm::FoldingSetNodeID ID;
3273 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003274 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003275 if (SubstTemplateTypeParmPackType *SubstParm
3276 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3277 return QualType(SubstParm, 0);
3278
3279 QualType Canon;
3280 if (!Parm->isCanonicalUnqualified()) {
3281 Canon = getCanonicalType(QualType(Parm, 0));
3282 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3283 ArgPack);
3284 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3285 }
3286
3287 SubstTemplateTypeParmPackType *SubstParm
3288 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3289 ArgPack);
3290 Types.push_back(SubstParm);
3291 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3292 return QualType(SubstParm, 0);
3293}
3294
Douglas Gregoreff93e02009-02-05 23:33:38 +00003295/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003296/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003297/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003298QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003299 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003300 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003301 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003302 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003303 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003304 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003305 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3306
3307 if (TypeParm)
3308 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003309
Chandler Carruth08836322011-05-01 00:51:33 +00003310 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003311 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003312 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003313
3314 TemplateTypeParmType *TypeCheck
3315 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3316 assert(!TypeCheck && "Template type parameter canonical type broken");
3317 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003318 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003319 TypeParm = new (*this, TypeAlignment)
3320 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003321
3322 Types.push_back(TypeParm);
3323 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3324
3325 return QualType(TypeParm, 0);
3326}
3327
John McCalle78aac42010-03-10 03:28:59 +00003328TypeSourceInfo *
3329ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3330 SourceLocation NameLoc,
3331 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003332 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003333 assert(!Name.getAsDependentTemplateName() &&
3334 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003335 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003336
3337 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003338 TemplateSpecializationTypeLoc TL =
3339 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003340 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003341 TL.setTemplateNameLoc(NameLoc);
3342 TL.setLAngleLoc(Args.getLAngleLoc());
3343 TL.setRAngleLoc(Args.getRAngleLoc());
3344 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3345 TL.setArgLocInfo(i, Args[i].getLocInfo());
3346 return DI;
3347}
3348
Mike Stump11289f42009-09-09 15:08:12 +00003349QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003350ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003351 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003352 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003353 assert(!Template.getAsDependentTemplateName() &&
3354 "No dependent template names here!");
3355
John McCall6b51f282009-11-23 01:53:49 +00003356 unsigned NumArgs = Args.size();
3357
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003358 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003359 ArgVec.reserve(NumArgs);
3360 for (unsigned i = 0; i != NumArgs; ++i)
3361 ArgVec.push_back(Args[i].getArgument());
3362
John McCall2408e322010-04-27 00:57:59 +00003363 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003364 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003365}
3366
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003367#ifndef NDEBUG
3368static bool hasAnyPackExpansions(const TemplateArgument *Args,
3369 unsigned NumArgs) {
3370 for (unsigned I = 0; I != NumArgs; ++I)
3371 if (Args[I].isPackExpansion())
3372 return true;
3373
3374 return true;
3375}
3376#endif
3377
John McCall0ad16662009-10-29 08:12:44 +00003378QualType
3379ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003380 const TemplateArgument *Args,
3381 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003382 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003383 assert(!Template.getAsDependentTemplateName() &&
3384 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003385 // Look through qualified template names.
3386 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3387 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003388
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003389 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003390 Template.getAsTemplateDecl() &&
3391 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003392 QualType CanonType;
3393 if (!Underlying.isNull())
3394 CanonType = getCanonicalType(Underlying);
3395 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003396 // We can get here with an alias template when the specialization contains
3397 // a pack expansion that does not match up with a parameter pack.
3398 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3399 "Caller must compute aliased type");
3400 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003401 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3402 NumArgs);
3403 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003404
Douglas Gregora8e02e72009-07-28 23:00:59 +00003405 // Allocate the (non-canonical) template specialization type, but don't
3406 // try to unique it: these types typically have location information that
3407 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003408 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3409 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003410 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003411 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003412 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003413 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3414 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003415
Douglas Gregor8bf42052009-02-09 18:46:07 +00003416 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003417 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003418}
3419
Mike Stump11289f42009-09-09 15:08:12 +00003420QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003421ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3422 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003423 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003424 assert(!Template.getAsDependentTemplateName() &&
3425 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003426
Douglas Gregore29139c2011-03-03 17:04:51 +00003427 // Look through qualified template names.
3428 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3429 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003430
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003431 // Build the canonical template specialization type.
3432 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003433 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003434 CanonArgs.reserve(NumArgs);
3435 for (unsigned I = 0; I != NumArgs; ++I)
3436 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3437
3438 // Determine whether this canonical template specialization type already
3439 // exists.
3440 llvm::FoldingSetNodeID ID;
3441 TemplateSpecializationType::Profile(ID, CanonTemplate,
3442 CanonArgs.data(), NumArgs, *this);
3443
Craig Topper36250ad2014-05-12 05:36:57 +00003444 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003445 TemplateSpecializationType *Spec
3446 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3447
3448 if (!Spec) {
3449 // Allocate a new canonical template specialization type.
3450 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3451 sizeof(TemplateArgument) * NumArgs),
3452 TypeAlignment);
3453 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3454 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003455 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003456 Types.push_back(Spec);
3457 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3458 }
3459
3460 assert(Spec->isDependentType() &&
3461 "Non-dependent template-id type must have a canonical type");
3462 return QualType(Spec, 0);
3463}
3464
3465QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003466ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3467 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003468 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003469 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003470 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003471
Craig Topper36250ad2014-05-12 05:36:57 +00003472 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003473 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003474 if (T)
3475 return QualType(T, 0);
3476
Douglas Gregorc42075a2010-02-04 18:10:26 +00003477 QualType Canon = NamedType;
3478 if (!Canon.isCanonical()) {
3479 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003480 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3481 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003482 (void)CheckT;
3483 }
3484
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003485 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003486 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003487 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003488 return QualType(T, 0);
3489}
3490
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003491QualType
Jay Foad39c79802011-01-12 09:06:06 +00003492ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003493 llvm::FoldingSetNodeID ID;
3494 ParenType::Profile(ID, InnerType);
3495
Craig Topper36250ad2014-05-12 05:36:57 +00003496 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003497 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3498 if (T)
3499 return QualType(T, 0);
3500
3501 QualType Canon = InnerType;
3502 if (!Canon.isCanonical()) {
3503 Canon = getCanonicalType(InnerType);
3504 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3505 assert(!CheckT && "Paren canonical type broken");
3506 (void)CheckT;
3507 }
3508
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003509 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003510 Types.push_back(T);
3511 ParenTypes.InsertNode(T, InsertPos);
3512 return QualType(T, 0);
3513}
3514
Douglas Gregor02085352010-03-31 20:19:30 +00003515QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3516 NestedNameSpecifier *NNS,
3517 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003518 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003519 if (Canon.isNull()) {
3520 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003521 ElaboratedTypeKeyword CanonKeyword = Keyword;
3522 if (Keyword == ETK_None)
3523 CanonKeyword = ETK_Typename;
3524
3525 if (CanonNNS != NNS || CanonKeyword != Keyword)
3526 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003527 }
3528
3529 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003530 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003531
Craig Topper36250ad2014-05-12 05:36:57 +00003532 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003533 DependentNameType *T
3534 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003535 if (T)
3536 return QualType(T, 0);
3537
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003538 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003539 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003540 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003541 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003542}
3543
Mike Stump11289f42009-09-09 15:08:12 +00003544QualType
John McCallc392f372010-06-11 00:33:02 +00003545ASTContext::getDependentTemplateSpecializationType(
3546 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003547 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003548 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003549 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003550 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003551 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003552 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3553 ArgCopy.push_back(Args[I].getArgument());
3554 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3555 ArgCopy.size(),
3556 ArgCopy.data());
3557}
3558
3559QualType
3560ASTContext::getDependentTemplateSpecializationType(
3561 ElaboratedTypeKeyword Keyword,
3562 NestedNameSpecifier *NNS,
3563 const IdentifierInfo *Name,
3564 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003565 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003566 assert((!NNS || NNS->isDependent()) &&
3567 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003568
Douglas Gregorc42075a2010-02-04 18:10:26 +00003569 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003570 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3571 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003572
Craig Topper36250ad2014-05-12 05:36:57 +00003573 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003574 DependentTemplateSpecializationType *T
3575 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003576 if (T)
3577 return QualType(T, 0);
3578
John McCallc392f372010-06-11 00:33:02 +00003579 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003580
John McCallc392f372010-06-11 00:33:02 +00003581 ElaboratedTypeKeyword CanonKeyword = Keyword;
3582 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3583
3584 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003585 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003586 for (unsigned I = 0; I != NumArgs; ++I) {
3587 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3588 if (!CanonArgs[I].structurallyEquals(Args[I]))
3589 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003590 }
3591
John McCallc392f372010-06-11 00:33:02 +00003592 QualType Canon;
3593 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3594 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3595 Name, NumArgs,
3596 CanonArgs.data());
3597
3598 // Find the insert position again.
3599 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3600 }
3601
3602 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3603 sizeof(TemplateArgument) * NumArgs),
3604 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003605 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003606 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003607 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003608 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003609 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003610}
3611
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003612QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003613 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003614 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003615 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003616
3617 assert(Pattern->containsUnexpandedParameterPack() &&
3618 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003619 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003620 PackExpansionType *T
3621 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3622 if (T)
3623 return QualType(T, 0);
3624
3625 QualType Canon;
3626 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003627 Canon = getCanonicalType(Pattern);
3628 // The canonical type might not contain an unexpanded parameter pack, if it
3629 // contains an alias template specialization which ignores one of its
3630 // parameters.
3631 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003632 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003633
Richard Smith68eea502012-07-16 00:20:35 +00003634 // Find the insert position again, in case we inserted an element into
3635 // PackExpansionTypes and invalidated our insert position.
3636 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3637 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003638 }
3639
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003640 T = new (*this, TypeAlignment)
3641 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003642 Types.push_back(T);
3643 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003644 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003645}
3646
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003647/// CmpProtocolNames - Comparison predicate for sorting protocols
3648/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003649static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3650 ObjCProtocolDecl *const *RHS) {
3651 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003652}
3653
John McCall8b07ec22010-05-15 11:32:37 +00003654static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003655 unsigned NumProtocols) {
3656 if (NumProtocols == 0) return true;
3657
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003658 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3659 return false;
3660
John McCallfc93cf92009-10-22 22:37:11 +00003661 for (unsigned i = 1; i != NumProtocols; ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003662 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003663 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003664 return false;
3665 return true;
3666}
3667
Craig Topper6a8c1512015-10-22 01:56:18 +00003668static void
3669SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003670 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003671 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003672
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003673 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003674 for (ObjCProtocolDecl *&P : Protocols)
3675 P = P->getCanonicalDecl();
3676
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003677 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003678 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3679 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003680}
3681
John McCall8b07ec22010-05-15 11:32:37 +00003682QualType ASTContext::getObjCObjectType(QualType BaseType,
3683 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003684 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003685 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003686 llvm::makeArrayRef(Protocols, NumProtocols),
3687 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003688}
3689
3690QualType ASTContext::getObjCObjectType(
3691 QualType baseType,
3692 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003693 ArrayRef<ObjCProtocolDecl *> protocols,
3694 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003695 // If the base type is an interface and there aren't any protocols or
3696 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003697 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3698 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003699 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003700
3701 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003702 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003703 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003704 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003705 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3706 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003707
Douglas Gregore9d95f12015-07-07 03:57:35 +00003708 // Determine the type arguments to be used for canonicalization,
3709 // which may be explicitly specified here or written on the base
3710 // type.
3711 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3712 if (effectiveTypeArgs.empty()) {
3713 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3714 effectiveTypeArgs = baseObject->getTypeArgs();
3715 }
John McCallfc93cf92009-10-22 22:37:11 +00003716
Douglas Gregore9d95f12015-07-07 03:57:35 +00003717 // Build the canonical type, which has the canonical base type and a
3718 // sorted-and-uniqued list of protocols and the type arguments
3719 // canonicalized.
3720 QualType canonical;
3721 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3722 effectiveTypeArgs.end(),
3723 [&](QualType type) {
3724 return type.isCanonical();
3725 });
3726 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3727 protocols.size());
3728 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3729 // Determine the canonical type arguments.
3730 ArrayRef<QualType> canonTypeArgs;
3731 SmallVector<QualType, 4> canonTypeArgsVec;
3732 if (!typeArgsAreCanonical) {
3733 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3734 for (auto typeArg : effectiveTypeArgs)
3735 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3736 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003737 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003738 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003739 }
3740
Douglas Gregore9d95f12015-07-07 03:57:35 +00003741 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3742 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3743 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003744 canonProtocolsVec.append(protocols.begin(), protocols.end());
3745 SortAndUniqueProtocols(canonProtocolsVec);
3746 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003747 } else {
3748 canonProtocols = protocols;
3749 }
3750
3751 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003752 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003753
John McCallfc93cf92009-10-22 22:37:11 +00003754 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003755 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3756 }
3757
Douglas Gregore9d95f12015-07-07 03:57:35 +00003758 unsigned size = sizeof(ObjCObjectTypeImpl);
3759 size += typeArgs.size() * sizeof(QualType);
3760 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3761 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003762 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003763 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3764 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003765
3766 Types.push_back(T);
3767 ObjCObjectTypes.InsertNode(T, InsertPos);
3768 return QualType(T, 0);
3769}
3770
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003771/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3772/// protocol list adopt all protocols in QT's qualified-id protocol
3773/// list.
3774bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3775 ObjCInterfaceDecl *IC) {
3776 if (!QT->isObjCQualifiedIdType())
3777 return false;
3778
3779 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3780 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003781 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003782 if (!IC->ClassImplementsProtocol(Proto, false))
3783 return false;
3784 }
3785 return true;
3786 }
3787 return false;
3788}
3789
3790/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3791/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3792/// of protocols.
3793bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3794 ObjCInterfaceDecl *IDecl) {
3795 if (!QT->isObjCQualifiedIdType())
3796 return false;
3797 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3798 if (!OPT)
3799 return false;
3800 if (!IDecl->hasDefinition())
3801 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003802 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3803 CollectInheritedProtocols(IDecl, InheritedProtocols);
3804 if (InheritedProtocols.empty())
3805 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003806 // Check that if every protocol in list of id<plist> conforms to a protcol
3807 // of IDecl's, then bridge casting is ok.
3808 bool Conforms = false;
3809 for (auto *Proto : OPT->quals()) {
3810 Conforms = false;
3811 for (auto *PI : InheritedProtocols) {
3812 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3813 Conforms = true;
3814 break;
3815 }
3816 }
3817 if (!Conforms)
3818 break;
3819 }
3820 if (Conforms)
3821 return true;
3822
Aaron Ballman83731462014-03-17 16:14:00 +00003823 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003824 // If both the right and left sides have qualifiers.
3825 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003826 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003827 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003828 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003829 break;
3830 }
3831 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003832 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003833 }
3834 return true;
3835}
3836
John McCall8b07ec22010-05-15 11:32:37 +00003837/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3838/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003839QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003840 llvm::FoldingSetNodeID ID;
3841 ObjCObjectPointerType::Profile(ID, ObjectT);
3842
Craig Topper36250ad2014-05-12 05:36:57 +00003843 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003844 if (ObjCObjectPointerType *QT =
3845 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3846 return QualType(QT, 0);
3847
3848 // Find the canonical object type.
3849 QualType Canonical;
3850 if (!ObjectT.isCanonical()) {
3851 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3852
3853 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003854 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3855 }
3856
Douglas Gregorf85bee62010-02-08 22:59:26 +00003857 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003858 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3859 ObjCObjectPointerType *QType =
3860 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003861
Steve Narofffb4330f2009-06-17 22:40:22 +00003862 Types.push_back(QType);
3863 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003864 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003865}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003866
Douglas Gregor1c283312010-08-11 12:19:30 +00003867/// getObjCInterfaceType - Return the unique reference to the type for the
3868/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003869QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3870 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003871 if (Decl->TypeForDecl)
3872 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003873
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003874 if (PrevDecl) {
3875 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3876 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3877 return QualType(PrevDecl->TypeForDecl, 0);
3878 }
3879
Douglas Gregor7671e532011-12-16 16:34:57 +00003880 // Prefer the definition, if there is one.
3881 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3882 Decl = Def;
3883
Douglas Gregor1c283312010-08-11 12:19:30 +00003884 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3885 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3886 Decl->TypeForDecl = T;
3887 Types.push_back(T);
3888 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003889}
3890
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003891/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3892/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003893/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003894/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003895/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003896QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003897 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003898 if (tofExpr->isTypeDependent()) {
3899 llvm::FoldingSetNodeID ID;
3900 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003901
Craig Topper36250ad2014-05-12 05:36:57 +00003902 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003903 DependentTypeOfExprType *Canon
3904 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3905 if (Canon) {
3906 // We already have a "canonical" version of an identical, dependent
3907 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003908 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003909 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003910 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003911 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003912 Canon
3913 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003914 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3915 toe = Canon;
3916 }
3917 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003918 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003919 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003920 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003921 Types.push_back(toe);
3922 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003923}
3924
Steve Naroffa773cd52007-08-01 18:02:17 +00003925/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003926/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003927/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003928/// an issue. This doesn't affect the type checker, since it operates
3929/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003930QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003931 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003932 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003933 Types.push_back(tot);
3934 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003935}
3936
Anders Carlssonad6bd352009-06-24 21:24:56 +00003937
Richard Smith8eb1d322014-06-05 20:13:13 +00003938/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3939/// nodes. This would never be helpful, since each such type has its own
3940/// expression, and would not give a significant memory saving, since there
3941/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003942QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003943 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003944
3945 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003946 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003947 // unique dependent type. Two such decltype-specifiers refer to the same
3948 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003949 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003950 llvm::FoldingSetNodeID ID;
3951 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003952
Craig Topper36250ad2014-05-12 05:36:57 +00003953 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003954 DependentDecltypeType *Canon
3955 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003956 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003957 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003958 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003959 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003960 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003961 dt = new (*this, TypeAlignment)
3962 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00003963 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00003964 dt = new (*this, TypeAlignment)
3965 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003966 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003967 Types.push_back(dt);
3968 return QualType(dt, 0);
3969}
3970
Alexis Hunte852b102011-05-24 22:41:36 +00003971/// getUnaryTransformationType - We don't unique these, since the memory
3972/// savings are minimal and these are rare.
3973QualType ASTContext::getUnaryTransformType(QualType BaseType,
3974 QualType UnderlyingType,
3975 UnaryTransformType::UTTKind Kind)
3976 const {
3977 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003978 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3979 Kind,
3980 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003981 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003982 Types.push_back(Ty);
3983 return QualType(Ty, 0);
3984}
3985
Richard Smith2a7d4812013-05-04 07:00:32 +00003986/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3987/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3988/// canonical deduced-but-dependent 'auto' type.
3989QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003990 bool IsDependent) const {
3991 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003992 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003993
Richard Smith2a7d4812013-05-04 07:00:32 +00003994 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00003995 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00003996 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003997 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003998 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3999 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004000
Richard Smith74aeef52013-04-26 16:15:35 +00004001 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00004002 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004003 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004004 Types.push_back(AT);
4005 if (InsertPos)
4006 AutoTypes.InsertNode(AT, InsertPos);
4007 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004008}
4009
Eli Friedman0dfb8892011-10-06 23:00:33 +00004010/// getAtomicType - Return the uniqued reference to the atomic type for
4011/// the given value type.
4012QualType ASTContext::getAtomicType(QualType T) const {
4013 // Unique pointers, to guarantee there is only one pointer of a particular
4014 // structure.
4015 llvm::FoldingSetNodeID ID;
4016 AtomicType::Profile(ID, T);
4017
Craig Topper36250ad2014-05-12 05:36:57 +00004018 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004019 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4020 return QualType(AT, 0);
4021
4022 // If the atomic value type isn't canonical, this won't be a canonical type
4023 // either, so fill in the canonical type field.
4024 QualType Canonical;
4025 if (!T.isCanonical()) {
4026 Canonical = getAtomicType(getCanonicalType(T));
4027
4028 // Get the new insert position for the node we care about.
4029 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004030 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004031 }
4032 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4033 Types.push_back(New);
4034 AtomicTypes.InsertNode(New, InsertPos);
4035 return QualType(New, 0);
4036}
4037
Richard Smith02e85f32011-04-14 22:09:26 +00004038/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4039QualType ASTContext::getAutoDeductType() const {
4040 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004041 AutoDeductTy = QualType(
4042 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004043 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004044 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004045 return AutoDeductTy;
4046}
4047
4048/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4049QualType ASTContext::getAutoRRefDeductType() const {
4050 if (AutoRRefDeductTy.isNull())
4051 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4052 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4053 return AutoRRefDeductTy;
4054}
4055
Chris Lattnerfb072462007-01-23 05:45:31 +00004056/// getTagDeclType - Return the unique reference to the type for the
4057/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004058QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004059 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004060 // FIXME: What is the design on getTagDeclType when it requires casting
4061 // away const? mutable?
4062 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004063}
4064
Mike Stump11289f42009-09-09 15:08:12 +00004065/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4066/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4067/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004068CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004069 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004070}
Chris Lattnerfb072462007-01-23 05:45:31 +00004071
Hans Wennborg27541db2011-10-27 08:29:09 +00004072/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4073CanQualType ASTContext::getIntMaxType() const {
4074 return getFromTargetType(Target->getIntMaxType());
4075}
4076
4077/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4078CanQualType ASTContext::getUIntMaxType() const {
4079 return getFromTargetType(Target->getUIntMaxType());
4080}
4081
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004082/// getSignedWCharType - Return the type of "signed wchar_t".
4083/// Used when in C++, as a GCC extension.
4084QualType ASTContext::getSignedWCharType() const {
4085 // FIXME: derive from "Target" ?
4086 return WCharTy;
4087}
4088
4089/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4090/// Used when in C++, as a GCC extension.
4091QualType ASTContext::getUnsignedWCharType() const {
4092 // FIXME: derive from "Target" ?
4093 return UnsignedIntTy;
4094}
4095
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004096QualType ASTContext::getIntPtrType() const {
4097 return getFromTargetType(Target->getIntPtrType());
4098}
4099
4100QualType ASTContext::getUIntPtrType() const {
4101 return getCorrespondingUnsignedType(getIntPtrType());
4102}
4103
Hans Wennborg27541db2011-10-27 08:29:09 +00004104/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004105/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4106QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004107 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004108}
4109
Eli Friedman4e91899e2012-11-27 02:58:24 +00004110/// \brief Return the unique type for "pid_t" defined in
4111/// <sys/types.h>. We need this to compute the correct type for vfork().
4112QualType ASTContext::getProcessIDType() const {
4113 return getFromTargetType(Target->getProcessIDType());
4114}
4115
Chris Lattnera21ad802008-04-02 05:18:44 +00004116//===----------------------------------------------------------------------===//
4117// Type Operators
4118//===----------------------------------------------------------------------===//
4119
Jay Foad39c79802011-01-12 09:06:06 +00004120CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004121 // Push qualifiers into arrays, and then discard any remaining
4122 // qualifiers.
4123 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004124 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004125 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004126 QualType Result;
4127 if (isa<ArrayType>(Ty)) {
4128 Result = getArrayDecayedType(QualType(Ty,0));
4129 } else if (isa<FunctionType>(Ty)) {
4130 Result = getPointerType(QualType(Ty, 0));
4131 } else {
4132 Result = QualType(Ty, 0);
4133 }
4134
4135 return CanQualType::CreateUnsafe(Result);
4136}
4137
John McCall6c9dd522011-01-18 07:41:22 +00004138QualType ASTContext::getUnqualifiedArrayType(QualType type,
4139 Qualifiers &quals) {
4140 SplitQualType splitType = type.getSplitUnqualifiedType();
4141
4142 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4143 // the unqualified desugared type and then drops it on the floor.
4144 // We then have to strip that sugar back off with
4145 // getUnqualifiedDesugaredType(), which is silly.
4146 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004147 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004148
4149 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004150 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004151 quals = splitType.Quals;
4152 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004153 }
4154
John McCall6c9dd522011-01-18 07:41:22 +00004155 // Otherwise, recurse on the array's element type.
4156 QualType elementType = AT->getElementType();
4157 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4158
4159 // If that didn't change the element type, AT has no qualifiers, so we
4160 // can just use the results in splitType.
4161 if (elementType == unqualElementType) {
4162 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004163 quals = splitType.Quals;
4164 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004165 }
4166
4167 // Otherwise, add in the qualifiers from the outermost type, then
4168 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004169 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004170
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004171 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004172 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004173 CAT->getSizeModifier(), 0);
4174 }
4175
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004176 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004177 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004178 }
4179
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004180 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004181 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004182 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004183 VAT->getSizeModifier(),
4184 VAT->getIndexTypeCVRQualifiers(),
4185 VAT->getBracketsRange());
4186 }
4187
4188 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004189 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004190 DSAT->getSizeModifier(), 0,
4191 SourceRange());
4192}
4193
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004194/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4195/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4196/// they point to and return true. If T1 and T2 aren't pointer types
4197/// or pointer-to-member types, or if they are not similar at this
4198/// level, returns false and leaves T1 and T2 unchanged. Top-level
4199/// qualifiers on T1 and T2 are ignored. This function will typically
4200/// be called in a loop that successively "unwraps" pointer and
4201/// pointer-to-member types to compare them at each level.
4202bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4203 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4204 *T2PtrType = T2->getAs<PointerType>();
4205 if (T1PtrType && T2PtrType) {
4206 T1 = T1PtrType->getPointeeType();
4207 T2 = T2PtrType->getPointeeType();
4208 return true;
4209 }
4210
4211 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4212 *T2MPType = T2->getAs<MemberPointerType>();
4213 if (T1MPType && T2MPType &&
4214 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4215 QualType(T2MPType->getClass(), 0))) {
4216 T1 = T1MPType->getPointeeType();
4217 T2 = T2MPType->getPointeeType();
4218 return true;
4219 }
4220
David Blaikiebbafb8a2012-03-11 07:00:24 +00004221 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004222 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4223 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4224 if (T1OPType && T2OPType) {
4225 T1 = T1OPType->getPointeeType();
4226 T2 = T2OPType->getPointeeType();
4227 return true;
4228 }
4229 }
4230
4231 // FIXME: Block pointers, too?
4232
4233 return false;
4234}
4235
Jay Foad39c79802011-01-12 09:06:06 +00004236DeclarationNameInfo
4237ASTContext::getNameForTemplate(TemplateName Name,
4238 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004239 switch (Name.getKind()) {
4240 case TemplateName::QualifiedTemplate:
4241 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004242 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004243 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4244 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004245
John McCalld9dfe3a2011-06-30 08:33:18 +00004246 case TemplateName::OverloadedTemplate: {
4247 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4248 // DNInfo work in progress: CHECKME: what about DNLoc?
4249 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4250 }
4251
4252 case TemplateName::DependentTemplate: {
4253 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004254 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004255 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004256 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4257 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004258 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004259 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4260 // DNInfo work in progress: FIXME: source locations?
4261 DeclarationNameLoc DNLoc;
4262 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4263 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4264 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004265 }
4266 }
4267
John McCalld9dfe3a2011-06-30 08:33:18 +00004268 case TemplateName::SubstTemplateTemplateParm: {
4269 SubstTemplateTemplateParmStorage *subst
4270 = Name.getAsSubstTemplateTemplateParm();
4271 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4272 NameLoc);
4273 }
4274
4275 case TemplateName::SubstTemplateTemplateParmPack: {
4276 SubstTemplateTemplateParmPackStorage *subst
4277 = Name.getAsSubstTemplateTemplateParmPack();
4278 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4279 NameLoc);
4280 }
4281 }
4282
4283 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004284}
4285
Jay Foad39c79802011-01-12 09:06:06 +00004286TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004287 switch (Name.getKind()) {
4288 case TemplateName::QualifiedTemplate:
4289 case TemplateName::Template: {
4290 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004291 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004292 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004293 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4294
4295 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004296 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004297 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004298
John McCalld9dfe3a2011-06-30 08:33:18 +00004299 case TemplateName::OverloadedTemplate:
4300 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004301
John McCalld9dfe3a2011-06-30 08:33:18 +00004302 case TemplateName::DependentTemplate: {
4303 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4304 assert(DTN && "Non-dependent template names must refer to template decls.");
4305 return DTN->CanonicalTemplateName;
4306 }
4307
4308 case TemplateName::SubstTemplateTemplateParm: {
4309 SubstTemplateTemplateParmStorage *subst
4310 = Name.getAsSubstTemplateTemplateParm();
4311 return getCanonicalTemplateName(subst->getReplacement());
4312 }
4313
4314 case TemplateName::SubstTemplateTemplateParmPack: {
4315 SubstTemplateTemplateParmPackStorage *subst
4316 = Name.getAsSubstTemplateTemplateParmPack();
4317 TemplateTemplateParmDecl *canonParameter
4318 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4319 TemplateArgument canonArgPack
4320 = getCanonicalTemplateArgument(subst->getArgumentPack());
4321 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4322 }
4323 }
4324
4325 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004326}
4327
Douglas Gregoradee3e32009-11-11 23:06:43 +00004328bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4329 X = getCanonicalTemplateName(X);
4330 Y = getCanonicalTemplateName(Y);
4331 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4332}
4333
Mike Stump11289f42009-09-09 15:08:12 +00004334TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004335ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004336 switch (Arg.getKind()) {
4337 case TemplateArgument::Null:
4338 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004339
Douglas Gregora8e02e72009-07-28 23:00:59 +00004340 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004341 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004342
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004343 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004344 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004345 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004346 }
Mike Stump11289f42009-09-09 15:08:12 +00004347
Eli Friedmanb826a002012-09-26 02:36:12 +00004348 case TemplateArgument::NullPtr:
4349 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4350 /*isNullPtr*/true);
4351
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004352 case TemplateArgument::Template:
4353 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004354
4355 case TemplateArgument::TemplateExpansion:
4356 return TemplateArgument(getCanonicalTemplateName(
4357 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004358 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004359
Douglas Gregora8e02e72009-07-28 23:00:59 +00004360 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004361 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004362
Douglas Gregora8e02e72009-07-28 23:00:59 +00004363 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004364 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004365
Douglas Gregora8e02e72009-07-28 23:00:59 +00004366 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004367 if (Arg.pack_size() == 0)
4368 return Arg;
4369
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004370 TemplateArgument *CanonArgs
4371 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004372 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004373 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004374 AEnd = Arg.pack_end();
4375 A != AEnd; (void)++A, ++Idx)
4376 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004377
Benjamin Kramercce63472015-08-05 09:40:22 +00004378 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004379 }
4380 }
4381
4382 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004383 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004384}
4385
Douglas Gregor333489b2009-03-27 23:10:48 +00004386NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004387ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004388 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004389 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004390
4391 switch (NNS->getKind()) {
4392 case NestedNameSpecifier::Identifier:
4393 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004394 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004395 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4396 NNS->getAsIdentifier());
4397
4398 case NestedNameSpecifier::Namespace:
4399 // A namespace is canonical; build a nested-name-specifier with
4400 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004401 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004402 NNS->getAsNamespace()->getOriginalNamespace());
4403
4404 case NestedNameSpecifier::NamespaceAlias:
4405 // A namespace is canonical; build a nested-name-specifier with
4406 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004407 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004408 NNS->getAsNamespaceAlias()->getNamespace()
4409 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004410
4411 case NestedNameSpecifier::TypeSpec:
4412 case NestedNameSpecifier::TypeSpecWithTemplate: {
4413 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004414
4415 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4416 // break it apart into its prefix and identifier, then reconsititute those
4417 // as the canonical nested-name-specifier. This is required to canonicalize
4418 // a dependent nested-name-specifier involving typedefs of dependent-name
4419 // types, e.g.,
4420 // typedef typename T::type T1;
4421 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004422 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4423 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004424 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004425
Eli Friedman5358a0a2012-03-03 04:09:56 +00004426 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4427 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4428 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004429 return NestedNameSpecifier::Create(*this, nullptr, false,
4430 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004431 }
4432
4433 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004434 case NestedNameSpecifier::Super:
4435 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004436 return NNS;
4437 }
4438
David Blaikie8a40f702012-01-17 06:56:22 +00004439 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004440}
4441
Chris Lattner7adf0762008-08-04 07:31:14 +00004442
Jay Foad39c79802011-01-12 09:06:06 +00004443const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004444 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004445 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004446 // Handle the common positive case fast.
4447 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4448 return AT;
4449 }
Mike Stump11289f42009-09-09 15:08:12 +00004450
John McCall8ccfcb52009-09-24 19:53:00 +00004451 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004452 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004453 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004454
John McCall8ccfcb52009-09-24 19:53:00 +00004455 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004456 // implements C99 6.7.3p8: "If the specification of an array type includes
4457 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004458
Chris Lattner7adf0762008-08-04 07:31:14 +00004459 // If we get here, we either have type qualifiers on the type, or we have
4460 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004461 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004462
John McCall33ddac02011-01-19 10:06:00 +00004463 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004464 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004465
Chris Lattner7adf0762008-08-04 07:31:14 +00004466 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004467 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004468 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004469 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004470
Chris Lattner7adf0762008-08-04 07:31:14 +00004471 // Otherwise, we have an array and we have qualifiers on it. Push the
4472 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004473 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004474
Chris Lattner7adf0762008-08-04 07:31:14 +00004475 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4476 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4477 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004478 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004479 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4480 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4481 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004482 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004483
Mike Stump11289f42009-09-09 15:08:12 +00004484 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004485 = dyn_cast<DependentSizedArrayType>(ATy))
4486 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004487 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004488 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004489 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004490 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004491 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004492
Chris Lattner7adf0762008-08-04 07:31:14 +00004493 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004494 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004495 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004496 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004497 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004498 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004499}
4500
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004501QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004502 if (T->isArrayType() || T->isFunctionType())
4503 return getDecayedType(T);
4504 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004505}
4506
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004507QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004508 T = getVariableArrayDecayedType(T);
4509 T = getAdjustedParameterType(T);
4510 return T.getUnqualifiedType();
4511}
4512
David Majnemerd09a51c2015-03-03 01:50:05 +00004513QualType ASTContext::getExceptionObjectType(QualType T) const {
4514 // C++ [except.throw]p3:
4515 // A throw-expression initializes a temporary object, called the exception
4516 // object, the type of which is determined by removing any top-level
4517 // cv-qualifiers from the static type of the operand of throw and adjusting
4518 // the type from "array of T" or "function returning T" to "pointer to T"
4519 // or "pointer to function returning T", [...]
4520 T = getVariableArrayDecayedType(T);
4521 if (T->isArrayType() || T->isFunctionType())
4522 T = getDecayedType(T);
4523 return T.getUnqualifiedType();
4524}
4525
Chris Lattnera21ad802008-04-02 05:18:44 +00004526/// getArrayDecayedType - Return the properly qualified result of decaying the
4527/// specified array type to a pointer. This operation is non-trivial when
4528/// handling typedefs etc. The canonical type of "T" must be an array type,
4529/// this returns a pointer to a properly qualified element of the array.
4530///
4531/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004532QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004533 // Get the element type with 'getAsArrayType' so that we don't lose any
4534 // typedefs in the element type of the array. This also handles propagation
4535 // of type qualifiers from the array type into the element type if present
4536 // (C99 6.7.3p8).
4537 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4538 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004539
Chris Lattner7adf0762008-08-04 07:31:14 +00004540 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004541
4542 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004543 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004544}
4545
John McCall33ddac02011-01-19 10:06:00 +00004546QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4547 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004548}
4549
John McCall33ddac02011-01-19 10:06:00 +00004550QualType ASTContext::getBaseElementType(QualType type) const {
4551 Qualifiers qs;
4552 while (true) {
4553 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004554 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004555 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004556
John McCall33ddac02011-01-19 10:06:00 +00004557 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004558 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004559 }
Mike Stump11289f42009-09-09 15:08:12 +00004560
John McCall33ddac02011-01-19 10:06:00 +00004561 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004562}
4563
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004564/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004565uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004566ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4567 uint64_t ElementCount = 1;
4568 do {
4569 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004570 CA = dyn_cast_or_null<ConstantArrayType>(
4571 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004572 } while (CA);
4573 return ElementCount;
4574}
4575
Steve Naroff0af91202007-04-27 21:51:21 +00004576/// getFloatingRank - Return a relative rank for floating point types.
4577/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004578static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004579 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004580 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004581
John McCall9dd450b2009-09-21 23:43:11 +00004582 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4583 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004584 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004585 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004586 case BuiltinType::Float: return FloatRank;
4587 case BuiltinType::Double: return DoubleRank;
4588 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004589 }
4590}
4591
Mike Stump11289f42009-09-09 15:08:12 +00004592/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4593/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004594/// 'typeDomain' is a real floating point or complex type.
4595/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004596QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4597 QualType Domain) const {
4598 FloatingRank EltRank = getFloatingRank(Size);
4599 if (Domain->isComplexType()) {
4600 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004601 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004602 case FloatRank: return FloatComplexTy;
4603 case DoubleRank: return DoubleComplexTy;
4604 case LongDoubleRank: return LongDoubleComplexTy;
4605 }
Steve Naroff0af91202007-04-27 21:51:21 +00004606 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004607
4608 assert(Domain->isRealFloatingType() && "Unknown domain!");
4609 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004610 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004611 case FloatRank: return FloatTy;
4612 case DoubleRank: return DoubleTy;
4613 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004614 }
David Blaikief47fa302012-01-17 02:30:50 +00004615 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004616}
4617
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004618/// getFloatingTypeOrder - Compare the rank of the two specified floating
4619/// point types, ignoring the domain of the type (i.e. 'double' ==
4620/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004621/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004622int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004623 FloatingRank LHSR = getFloatingRank(LHS);
4624 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004625
Chris Lattnerb90739d2008-04-06 23:38:49 +00004626 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004627 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004628 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004629 return 1;
4630 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004631}
4632
Chris Lattner76a00cf2008-04-06 22:59:24 +00004633/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4634/// routine will assert if passed a built-in type that isn't an integer or enum,
4635/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004636unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004637 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004638
Chris Lattner76a00cf2008-04-06 22:59:24 +00004639 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004640 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004641 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004642 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004643 case BuiltinType::Char_S:
4644 case BuiltinType::Char_U:
4645 case BuiltinType::SChar:
4646 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004647 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004648 case BuiltinType::Short:
4649 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004650 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004651 case BuiltinType::Int:
4652 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004653 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004654 case BuiltinType::Long:
4655 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004656 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004657 case BuiltinType::LongLong:
4658 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004659 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004660 case BuiltinType::Int128:
4661 case BuiltinType::UInt128:
4662 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004663 }
4664}
4665
Eli Friedman629ffb92009-08-20 04:21:42 +00004666/// \brief Whether this is a promotable bitfield reference according
4667/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4668///
4669/// \returns the type this bit-field will promote to, or NULL if no
4670/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004671QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004672 if (E->isTypeDependent() || E->isValueDependent())
4673 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004674
4675 // FIXME: We should not do this unless E->refersToBitField() is true. This
4676 // matters in C where getSourceBitField() will find bit-fields for various
4677 // cases where the source expression is not a bit-field designator.
4678
John McCalld25db7e2013-05-06 21:39:12 +00004679 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004680 if (!Field)
4681 return QualType();
4682
4683 QualType FT = Field->getType();
4684
Richard Smithcaf33902011-10-10 18:28:20 +00004685 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004686 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004687 // C++ [conv.prom]p5:
4688 // A prvalue for an integral bit-field can be converted to a prvalue of type
4689 // int if int can represent all the values of the bit-field; otherwise, it
4690 // can be converted to unsigned int if unsigned int can represent all the
4691 // values of the bit-field. If the bit-field is larger yet, no integral
4692 // promotion applies to it.
4693 // C11 6.3.1.1/2:
4694 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4695 // If an int can represent all values of the original type (as restricted by
4696 // the width, for a bit-field), the value is converted to an int; otherwise,
4697 // it is converted to an unsigned int.
4698 //
4699 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4700 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004701 if (BitWidth < IntSize)
4702 return IntTy;
4703
4704 if (BitWidth == IntSize)
4705 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4706
4707 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004708 // like the base type. GCC has some weird bugs in this area that we
4709 // deliberately do not follow (GCC follows a pre-standard resolution to
4710 // C's DR315 which treats bit-width as being part of the type, and this leaks
4711 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004712 return QualType();
4713}
4714
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004715/// getPromotedIntegerType - Returns the type that Promotable will
4716/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4717/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004718QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004719 assert(!Promotable.isNull());
4720 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004721 if (const EnumType *ET = Promotable->getAs<EnumType>())
4722 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004723
4724 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4725 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4726 // (3.9.1) can be converted to a prvalue of the first of the following
4727 // types that can represent all the values of its underlying type:
4728 // int, unsigned int, long int, unsigned long int, long long int, or
4729 // unsigned long long int [...]
4730 // FIXME: Is there some better way to compute this?
4731 if (BT->getKind() == BuiltinType::WChar_S ||
4732 BT->getKind() == BuiltinType::WChar_U ||
4733 BT->getKind() == BuiltinType::Char16 ||
4734 BT->getKind() == BuiltinType::Char32) {
4735 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4736 uint64_t FromSize = getTypeSize(BT);
4737 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4738 LongLongTy, UnsignedLongLongTy };
4739 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4740 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4741 if (FromSize < ToSize ||
4742 (FromSize == ToSize &&
4743 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4744 return PromoteTypes[Idx];
4745 }
4746 llvm_unreachable("char type should fit into long long");
4747 }
4748 }
4749
4750 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004751 if (Promotable->isSignedIntegerType())
4752 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004753 uint64_t PromotableSize = getIntWidth(Promotable);
4754 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004755 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4756 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4757}
4758
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004759/// \brief Recurses in pointer/array types until it finds an objc retainable
4760/// type and returns its ownership.
4761Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4762 while (!T.isNull()) {
4763 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4764 return T.getObjCLifetime();
4765 if (T->isArrayType())
4766 T = getBaseElementType(T);
4767 else if (const PointerType *PT = T->getAs<PointerType>())
4768 T = PT->getPointeeType();
4769 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004770 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004771 else
4772 break;
4773 }
4774
4775 return Qualifiers::OCL_None;
4776}
4777
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004778static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4779 // Incomplete enum types are not treated as integer types.
4780 // FIXME: In C++, enum types are never integer types.
4781 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4782 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004783 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004784}
4785
Mike Stump11289f42009-09-09 15:08:12 +00004786/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004787/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004788/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004789int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004790 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4791 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004792
4793 // Unwrap enums to their underlying type.
4794 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4795 LHSC = getIntegerTypeForEnum(ET);
4796 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4797 RHSC = getIntegerTypeForEnum(ET);
4798
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004799 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004800
Chris Lattner76a00cf2008-04-06 22:59:24 +00004801 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4802 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004803
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004804 unsigned LHSRank = getIntegerRank(LHSC);
4805 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004806
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004807 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4808 if (LHSRank == RHSRank) return 0;
4809 return LHSRank > RHSRank ? 1 : -1;
4810 }
Mike Stump11289f42009-09-09 15:08:12 +00004811
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004812 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4813 if (LHSUnsigned) {
4814 // If the unsigned [LHS] type is larger, return it.
4815 if (LHSRank >= RHSRank)
4816 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004817
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004818 // If the signed type can represent all values of the unsigned type, it
4819 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004820 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004821 return -1;
4822 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004823
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004824 // If the unsigned [RHS] type is larger, return it.
4825 if (RHSRank >= LHSRank)
4826 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004827
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004828 // If the signed type can represent all values of the unsigned type, it
4829 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004830 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004831 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004832}
Anders Carlsson98f07902007-08-17 05:31:46 +00004833
Mike Stump11289f42009-09-09 15:08:12 +00004834// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004835QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004836 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004837 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004838 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004839
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004840 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004841
Anders Carlsson98f07902007-08-17 05:31:46 +00004842 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004843 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004844 // int flags;
4845 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004846 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004847 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004848 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004849 FieldTypes[3] = LongTy;
4850
Anders Carlsson98f07902007-08-17 05:31:46 +00004851 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004852 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004853 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004854 SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004855 SourceLocation(), nullptr,
4856 FieldTypes[i], /*TInfo=*/nullptr,
4857 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004858 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004859 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004860 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004861 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004862 }
4863
Douglas Gregord5058122010-02-11 01:19:42 +00004864 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004865 }
Mike Stump11289f42009-09-09 15:08:12 +00004866
Anders Carlsson98f07902007-08-17 05:31:46 +00004867 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004868}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004869
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004870QualType ASTContext::getObjCSuperType() const {
4871 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004872 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004873 TUDecl->addDecl(ObjCSuperTypeDecl);
4874 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4875 }
4876 return ObjCSuperType;
4877}
4878
Douglas Gregor512b0772009-04-23 22:29:11 +00004879void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004880 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004881 assert(Rec && "Invalid CFConstantStringType");
4882 CFConstantStringTypeDecl = Rec->getDecl();
4883}
4884
Jay Foad39c79802011-01-12 09:06:06 +00004885QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004886 if (BlockDescriptorType)
4887 return getTagDeclType(BlockDescriptorType);
4888
Alp Toker2dea15b2013-12-17 01:22:38 +00004889 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004890 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004891 RD = buildImplicitRecord("__block_descriptor");
4892 RD->startDefinition();
4893
Mike Stumpd0153282009-10-20 02:12:22 +00004894 QualType FieldTypes[] = {
4895 UnsignedLongTy,
4896 UnsignedLongTy,
4897 };
4898
Craig Topperd6d31ac2013-07-15 08:24:27 +00004899 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004900 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004901 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004902 };
4903
4904 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004905 FieldDecl *Field = FieldDecl::Create(
4906 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004907 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4908 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004909 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004910 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004911 }
4912
Alp Toker2dea15b2013-12-17 01:22:38 +00004913 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004914
Alp Toker2dea15b2013-12-17 01:22:38 +00004915 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004916
4917 return getTagDeclType(BlockDescriptorType);
4918}
4919
Jay Foad39c79802011-01-12 09:06:06 +00004920QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004921 if (BlockDescriptorExtendedType)
4922 return getTagDeclType(BlockDescriptorExtendedType);
4923
Alp Toker2dea15b2013-12-17 01:22:38 +00004924 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004925 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004926 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4927 RD->startDefinition();
4928
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004929 QualType FieldTypes[] = {
4930 UnsignedLongTy,
4931 UnsignedLongTy,
4932 getPointerType(VoidPtrTy),
4933 getPointerType(VoidPtrTy)
4934 };
4935
Craig Topperd6d31ac2013-07-15 08:24:27 +00004936 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004937 "reserved",
4938 "Size",
4939 "CopyFuncPtr",
4940 "DestroyFuncPtr"
4941 };
4942
4943 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004944 FieldDecl *Field = FieldDecl::Create(
4945 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004946 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4947 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00004948 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004949 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004950 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004951 }
4952
Alp Toker2dea15b2013-12-17 01:22:38 +00004953 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004954
Alp Toker2dea15b2013-12-17 01:22:38 +00004955 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004956 return getTagDeclType(BlockDescriptorExtendedType);
4957}
4958
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004959/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4960/// requires copy/dispose. Note that this must match the logic
4961/// in buildByrefHelpers.
4962bool ASTContext::BlockRequiresCopying(QualType Ty,
4963 const VarDecl *D) {
4964 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4965 const Expr *copyExpr = getBlockVarCopyInits(D);
4966 if (!copyExpr && record->hasTrivialDestructor()) return false;
4967
Mike Stump94967902009-10-21 18:16:27 +00004968 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004969 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004970
4971 if (!Ty->isObjCRetainableType()) return false;
4972
4973 Qualifiers qs = Ty.getQualifiers();
4974
4975 // If we have lifetime, that dominates.
4976 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004977 switch (lifetime) {
4978 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4979
4980 // These are just bits as far as the runtime is concerned.
4981 case Qualifiers::OCL_ExplicitNone:
4982 case Qualifiers::OCL_Autoreleasing:
4983 return false;
4984
4985 // Tell the runtime that this is ARC __weak, called by the
4986 // byref routines.
4987 case Qualifiers::OCL_Weak:
4988 // ARC __strong __block variables need to be retained.
4989 case Qualifiers::OCL_Strong:
4990 return true;
4991 }
4992 llvm_unreachable("fell out of lifetime switch!");
4993 }
4994 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4995 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004996}
4997
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004998bool ASTContext::getByrefLifetime(QualType Ty,
4999 Qualifiers::ObjCLifetime &LifeTime,
5000 bool &HasByrefExtendedLayout) const {
5001
5002 if (!getLangOpts().ObjC1 ||
5003 getLangOpts().getGC() != LangOptions::NonGC)
5004 return false;
5005
5006 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005007 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005008 HasByrefExtendedLayout = true;
5009 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005010 } else if ((LifeTime = Ty.getObjCLifetime())) {
5011 // Honor the ARC qualifiers.
5012 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5013 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005014 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005015 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005016 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005017 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005018 return true;
5019}
5020
Douglas Gregorbab8a962011-09-08 01:46:34 +00005021TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5022 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005023 ObjCInstanceTypeDecl =
5024 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005025 return ObjCInstanceTypeDecl;
5026}
5027
Anders Carlsson18acd442007-10-29 06:33:42 +00005028// This returns true if a type has been typedefed to BOOL:
5029// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005030static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005031 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005032 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5033 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005034
Anders Carlssond8499822007-10-29 05:01:08 +00005035 return false;
5036}
5037
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005038/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005039/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005040CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005041 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5042 return CharUnits::Zero();
5043
Ken Dyck40775002010-01-11 17:06:35 +00005044 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005045
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005046 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005047 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005048 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005049 // Treat arrays as pointers, since that's how they're passed in.
5050 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005051 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005052 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005053}
5054
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005055bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005056 return getTargetInfo().getCXXABI().isMicrosoft() &&
5057 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005058 VD->getType()->isIntegralOrEnumerationType() &&
5059 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005060}
5061
Ken Dyck40775002010-01-11 17:06:35 +00005062static inline
5063std::string charUnitsToString(const CharUnits &CU) {
5064 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005065}
5066
John McCall351762c2011-02-07 10:33:21 +00005067/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005068/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005069std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5070 std::string S;
5071
David Chisnall950a9512009-11-17 19:33:30 +00005072 const BlockDecl *Decl = Expr->getBlockDecl();
5073 QualType BlockTy =
5074 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5075 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005076 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005077 getObjCEncodingForMethodParameter(
5078 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5079 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005080 else
Alp Toker314cc812014-01-25 16:55:45 +00005081 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005082 // Compute size of all parameters.
5083 // Start with computing size of a pointer in number of bytes.
5084 // FIXME: There might(should) be a better way of doing this computation!
5085 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005086 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5087 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005088 for (auto PI : Decl->params()) {
5089 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005090 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005091 if (sz.isZero())
5092 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005093 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005094 ParmOffset += sz;
5095 }
5096 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005097 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005098 // Block pointer and offset.
5099 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005100
5101 // Argument types.
5102 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005103 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005104 QualType PType = PVDecl->getOriginalType();
5105 if (const ArrayType *AT =
5106 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5107 // Use array's original type only if it has known number of
5108 // elements.
5109 if (!isa<ConstantArrayType>(AT))
5110 PType = PVDecl->getType();
5111 } else if (PType->isFunctionType())
5112 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005113 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005114 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5115 S, true /*Extended*/);
5116 else
5117 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005118 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005119 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005120 }
John McCall351762c2011-02-07 10:33:21 +00005121
5122 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005123}
5124
Douglas Gregora9d84932011-05-27 01:19:52 +00005125bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005126 std::string& S) {
5127 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005128 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005129 CharUnits ParmOffset;
5130 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005131 for (auto PI : Decl->params()) {
5132 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005133 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005134 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005135 continue;
5136
David Chisnall50e4eba2010-12-30 14:05:53 +00005137 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005138 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005139 ParmOffset += sz;
5140 }
5141 S += charUnitsToString(ParmOffset);
5142 ParmOffset = CharUnits::Zero();
5143
5144 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005145 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005146 QualType PType = PVDecl->getOriginalType();
5147 if (const ArrayType *AT =
5148 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5149 // Use array's original type only if it has known number of
5150 // elements.
5151 if (!isa<ConstantArrayType>(AT))
5152 PType = PVDecl->getType();
5153 } else if (PType->isFunctionType())
5154 PType = PVDecl->getType();
5155 getObjCEncodingForType(PType, S);
5156 S += charUnitsToString(ParmOffset);
5157 ParmOffset += getObjCEncodingTypeSize(PType);
5158 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005159
5160 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005161}
5162
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005163/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5164/// method parameter or return type. If Extended, include class names and
5165/// block object types.
5166void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5167 QualType T, std::string& S,
5168 bool Extended) const {
5169 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5170 getObjCEncodingForTypeQualifier(QT, S);
5171 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005172 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005173 true /*OutermostType*/,
5174 false /*EncodingProperty*/,
5175 false /*StructField*/,
5176 Extended /*EncodeBlockParameters*/,
5177 Extended /*EncodeClassNames*/);
5178}
5179
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005180/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005181/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005182bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005183 std::string& S,
5184 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005185 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005186 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005187 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5188 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005189 // Compute size of all parameters.
5190 // Start with computing size of a pointer in number of bytes.
5191 // FIXME: There might(should) be a better way of doing this computation!
5192 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005193 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005194 // The first two arguments (self and _cmd) are pointers; account for
5195 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005196 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005197 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005198 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005199 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005200 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005201 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005202 continue;
5203
Ken Dyck40775002010-01-11 17:06:35 +00005204 assert (sz.isPositive() &&
5205 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005206 ParmOffset += sz;
5207 }
Ken Dyck40775002010-01-11 17:06:35 +00005208 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005209 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005210 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005211
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005212 // Argument types.
5213 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005214 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005215 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005216 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005217 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005218 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005219 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5220 // Use array's original type only if it has known number of
5221 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005222 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005223 PType = PVDecl->getType();
5224 } else if (PType->isFunctionType())
5225 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005226 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5227 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005228 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005229 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005230 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005231
5232 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005233}
5234
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005235ObjCPropertyImplDecl *
5236ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5237 const ObjCPropertyDecl *PD,
5238 const Decl *Container) const {
5239 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005240 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005241 if (const ObjCCategoryImplDecl *CID =
5242 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005243 for (auto *PID : CID->property_impls())
5244 if (PID->getPropertyDecl() == PD)
5245 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005246 } else {
5247 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5248 for (auto *PID : OID->property_impls())
5249 if (PID->getPropertyDecl() == PD)
5250 return PID;
5251 }
5252 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005253}
5254
Daniel Dunbar4932b362008-08-28 04:38:10 +00005255/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005256/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005257/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5258/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005259/// Property attributes are stored as a comma-delimited C string. The simple
5260/// attributes readonly and bycopy are encoded as single characters. The
5261/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5262/// encoded as single characters, followed by an identifier. Property types
5263/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005264/// these attributes are defined by the following enumeration:
5265/// @code
5266/// enum PropertyAttributes {
5267/// kPropertyReadOnly = 'R', // property is read-only.
5268/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5269/// kPropertyByref = '&', // property is a reference to the value last assigned
5270/// kPropertyDynamic = 'D', // property is dynamic
5271/// kPropertyGetter = 'G', // followed by getter selector name
5272/// kPropertySetter = 'S', // followed by setter selector name
5273/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005274/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005275/// kPropertyWeak = 'W' // 'weak' property
5276/// kPropertyStrong = 'P' // property GC'able
5277/// kPropertyNonAtomic = 'N' // property non-atomic
5278/// };
5279/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005280void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005281 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005282 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005283 // Collect information from the property implementation decl(s).
5284 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005285 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005286
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005287 if (ObjCPropertyImplDecl *PropertyImpDecl =
5288 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5289 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5290 Dynamic = true;
5291 else
5292 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005293 }
5294
5295 // FIXME: This is not very efficient.
5296 S = "T";
5297
5298 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005299 // GCC has some special rules regarding encoding of properties which
5300 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005301 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005302
5303 if (PD->isReadOnly()) {
5304 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005305 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5306 S += ",C";
5307 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5308 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005309 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5310 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005311 } else {
5312 switch (PD->getSetterKind()) {
5313 case ObjCPropertyDecl::Assign: break;
5314 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005315 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005316 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005317 }
5318 }
5319
5320 // It really isn't clear at all what this means, since properties
5321 // are "dynamic by default".
5322 if (Dynamic)
5323 S += ",D";
5324
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005325 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5326 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005327
Daniel Dunbar4932b362008-08-28 04:38:10 +00005328 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5329 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005330 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005331 }
5332
5333 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5334 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005335 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005336 }
5337
5338 if (SynthesizePID) {
5339 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5340 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005341 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005342 }
5343
5344 // FIXME: OBJCGC: weak & strong
5345}
5346
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005347/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005348/// Another legacy compatibility encoding: 32-bit longs are encoded as
5349/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005350/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5351///
5352void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005353 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005354 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005355 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005356 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005357 else
Jay Foad39c79802011-01-12 09:06:06 +00005358 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005359 PointeeTy = IntTy;
5360 }
5361 }
5362}
5363
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005364void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005365 const FieldDecl *Field,
5366 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005367 // We follow the behavior of gcc, expanding structures which are
5368 // directly pointed to, and expanding embedded structures. Note that
5369 // these rules are sufficient to prevent recursive encoding of the
5370 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005371 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005372 true /* outermost type */, false, false,
5373 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005374}
5375
Joe Groff98ac7d22014-07-07 22:25:15 +00005376void ASTContext::getObjCEncodingForPropertyType(QualType T,
5377 std::string& S) const {
5378 // Encode result type.
5379 // GCC has some special rules regarding encoding of properties which
5380 // closely resembles encoding of ivars.
5381 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5382 true /* outermost type */,
5383 true /* encoding property */);
5384}
5385
John McCall393a78d2012-12-20 02:45:14 +00005386static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5387 BuiltinType::Kind kind) {
5388 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005389 case BuiltinType::Void: return 'v';
5390 case BuiltinType::Bool: return 'B';
5391 case BuiltinType::Char_U:
5392 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005393 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005394 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005395 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005396 case BuiltinType::UInt: return 'I';
5397 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005398 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005399 case BuiltinType::UInt128: return 'T';
5400 case BuiltinType::ULongLong: return 'Q';
5401 case BuiltinType::Char_S:
5402 case BuiltinType::SChar: return 'c';
5403 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005404 case BuiltinType::WChar_S:
5405 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005406 case BuiltinType::Int: return 'i';
5407 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005408 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005409 case BuiltinType::LongLong: return 'q';
5410 case BuiltinType::Int128: return 't';
5411 case BuiltinType::Float: return 'f';
5412 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005413 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005414 case BuiltinType::NullPtr: return '*'; // like char*
5415
5416 case BuiltinType::Half:
5417 // FIXME: potentially need @encodes for these!
5418 return ' ';
5419
5420 case BuiltinType::ObjCId:
5421 case BuiltinType::ObjCClass:
5422 case BuiltinType::ObjCSel:
5423 llvm_unreachable("@encoding ObjC primitive type");
5424
5425 // OpenCL and placeholder types don't need @encodings.
5426 case BuiltinType::OCLImage1d:
5427 case BuiltinType::OCLImage1dArray:
5428 case BuiltinType::OCLImage1dBuffer:
5429 case BuiltinType::OCLImage2d:
5430 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005431 case BuiltinType::OCLImage2dDepth:
5432 case BuiltinType::OCLImage2dArrayDepth:
5433 case BuiltinType::OCLImage2dMSAA:
5434 case BuiltinType::OCLImage2dArrayMSAA:
5435 case BuiltinType::OCLImage2dMSAADepth:
5436 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005437 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005438 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005439 case BuiltinType::OCLClkEvent:
5440 case BuiltinType::OCLQueue:
5441 case BuiltinType::OCLNDRange:
5442 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005443 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005444 case BuiltinType::Dependent:
5445#define BUILTIN_TYPE(KIND, ID)
5446#define PLACEHOLDER_TYPE(KIND, ID) \
5447 case BuiltinType::KIND:
5448#include "clang/AST/BuiltinTypes.def"
5449 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005450 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005451 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005452}
5453
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005454static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5455 EnumDecl *Enum = ET->getDecl();
5456
5457 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5458 if (!Enum->isFixed())
5459 return 'i';
5460
5461 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005462 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5463 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005464}
5465
Jay Foad39c79802011-01-12 09:06:06 +00005466static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005467 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005468 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005469 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005470 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5471 // The GNU runtime requires more information; bitfields are encoded as b,
5472 // then the offset (in bits) of the first element, then the type of the
5473 // bitfield, then the size in bits. For example, in this structure:
5474 //
5475 // struct
5476 // {
5477 // int integer;
5478 // int flags:2;
5479 // };
5480 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5481 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5482 // information is not especially sensible, but we're stuck with it for
5483 // compatibility with GCC, although providing it breaks anything that
5484 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005485 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005486 const RecordDecl *RD = FD->getParent();
5487 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005488 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005489 if (const EnumType *ET = T->getAs<EnumType>())
5490 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005491 else {
5492 const BuiltinType *BT = T->castAs<BuiltinType>();
5493 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5494 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005495 }
Richard Smithcaf33902011-10-10 18:28:20 +00005496 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005497}
5498
Daniel Dunbar07d07852009-10-18 21:17:35 +00005499// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005500void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5501 bool ExpandPointedToStructures,
5502 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005503 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005504 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005505 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005506 bool StructField,
5507 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005508 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005509 bool EncodePointerToObjCTypedef,
5510 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005511 CanQualType CT = getCanonicalType(T);
5512 switch (CT->getTypeClass()) {
5513 case Type::Builtin:
5514 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005515 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005516 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005517 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5518 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5519 else
5520 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005521 return;
Mike Stump11289f42009-09-09 15:08:12 +00005522
John McCall393a78d2012-12-20 02:45:14 +00005523 case Type::Complex: {
5524 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005525 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005526 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005527 return;
5528 }
John McCall393a78d2012-12-20 02:45:14 +00005529
5530 case Type::Atomic: {
5531 const AtomicType *AT = T->castAs<AtomicType>();
5532 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005533 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005534 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005535 }
John McCall393a78d2012-12-20 02:45:14 +00005536
5537 // encoding for pointer or reference types.
5538 case Type::Pointer:
5539 case Type::LValueReference:
5540 case Type::RValueReference: {
5541 QualType PointeeTy;
5542 if (isa<PointerType>(CT)) {
5543 const PointerType *PT = T->castAs<PointerType>();
5544 if (PT->isObjCSelType()) {
5545 S += ':';
5546 return;
5547 }
5548 PointeeTy = PT->getPointeeType();
5549 } else {
5550 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5551 }
5552
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005553 bool isReadOnly = false;
5554 // For historical/compatibility reasons, the read-only qualifier of the
5555 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5556 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005557 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005558 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005559 if (OutermostType && T.isConstQualified()) {
5560 isReadOnly = true;
5561 S += 'r';
5562 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005563 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005564 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005565 while (P->getAs<PointerType>())
5566 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005567 if (P.isConstQualified()) {
5568 isReadOnly = true;
5569 S += 'r';
5570 }
5571 }
5572 if (isReadOnly) {
5573 // Another legacy compatibility encoding. Some ObjC qualifier and type
5574 // combinations need to be rearranged.
5575 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005576 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005577 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005578 }
Mike Stump11289f42009-09-09 15:08:12 +00005579
Anders Carlssond8499822007-10-29 05:01:08 +00005580 if (PointeeTy->isCharType()) {
5581 // char pointer types should be encoded as '*' unless it is a
5582 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005583 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005584 S += '*';
5585 return;
5586 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005587 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005588 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5589 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5590 S += '#';
5591 return;
5592 }
5593 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5594 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5595 S += '@';
5596 return;
5597 }
5598 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005599 }
Anders Carlssond8499822007-10-29 05:01:08 +00005600 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005601 getLegacyIntegralTypeEncoding(PointeeTy);
5602
Mike Stump11289f42009-09-09 15:08:12 +00005603 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005604 nullptr, false, false, false, false, false, false,
5605 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005606 return;
5607 }
John McCall393a78d2012-12-20 02:45:14 +00005608
5609 case Type::ConstantArray:
5610 case Type::IncompleteArray:
5611 case Type::VariableArray: {
5612 const ArrayType *AT = cast<ArrayType>(CT);
5613
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005614 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005615 // Incomplete arrays are encoded as a pointer to the array element.
5616 S += '^';
5617
Mike Stump11289f42009-09-09 15:08:12 +00005618 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005619 false, ExpandStructures, FD);
5620 } else {
5621 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005622
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005623 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5624 S += llvm::utostr(CAT->getSize().getZExtValue());
5625 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005626 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005627 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5628 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005629 S += '0';
5630 }
Mike Stump11289f42009-09-09 15:08:12 +00005631
5632 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005633 false, ExpandStructures, FD,
5634 false, false, false, false, false, false,
5635 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005636 S += ']';
5637 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005638 return;
5639 }
Mike Stump11289f42009-09-09 15:08:12 +00005640
John McCall393a78d2012-12-20 02:45:14 +00005641 case Type::FunctionNoProto:
5642 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005643 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005644 return;
Mike Stump11289f42009-09-09 15:08:12 +00005645
John McCall393a78d2012-12-20 02:45:14 +00005646 case Type::Record: {
5647 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005648 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005649 // Anonymous structures print as '?'
5650 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5651 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005652 if (ClassTemplateSpecializationDecl *Spec
5653 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5654 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005655 llvm::raw_string_ostream OS(S);
5656 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005657 TemplateArgs.data(),
5658 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005659 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005660 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005661 } else {
5662 S += '?';
5663 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005664 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005665 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005666 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005667 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005668 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005669 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005670 if (FD) {
5671 S += '"';
5672 S += Field->getNameAsString();
5673 S += '"';
5674 }
Mike Stump11289f42009-09-09 15:08:12 +00005675
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005676 // Special case bit-fields.
5677 if (Field->isBitField()) {
5678 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005679 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005680 } else {
5681 QualType qt = Field->getType();
5682 getLegacyIntegralTypeEncoding(qt);
5683 getObjCEncodingForTypeImpl(qt, S, false, true,
5684 FD, /*OutermostType*/false,
5685 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005686 /*StructField*/true,
5687 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005688 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005689 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005690 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005691 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005692 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005693 return;
5694 }
Mike Stump11289f42009-09-09 15:08:12 +00005695
John McCall393a78d2012-12-20 02:45:14 +00005696 case Type::BlockPointer: {
5697 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005698 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005699 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005700 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005701
5702 S += '<';
5703 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005704 getObjCEncodingForTypeImpl(
5705 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5706 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005707 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5708 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005709 // Block self
5710 S += "@?";
5711 // Block parameters
5712 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005713 for (const auto &I : FPT->param_types())
5714 getObjCEncodingForTypeImpl(
5715 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5716 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005717 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5718 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005719 }
5720 S += '>';
5721 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005722 return;
5723 }
Mike Stump11289f42009-09-09 15:08:12 +00005724
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005725 case Type::ObjCObject: {
5726 // hack to match legacy encoding of *id and *Class
5727 QualType Ty = getObjCObjectPointerType(CT);
5728 if (Ty->isObjCIdType()) {
5729 S += "{objc_object=}";
5730 return;
5731 }
5732 else if (Ty->isObjCClassType()) {
5733 S += "{objc_class=}";
5734 return;
5735 }
5736 }
5737
John McCall393a78d2012-12-20 02:45:14 +00005738 case Type::ObjCInterface: {
5739 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005740 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005741 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005742 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005743 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005744 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005745 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005746 DeepCollectObjCIvars(OI, true, Ivars);
5747 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005748 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005749 if (Field->isBitField())
5750 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005751 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005752 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5753 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005754 EncodePointerToObjCTypedef,
5755 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005756 }
5757 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005758 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005759 }
Mike Stump11289f42009-09-09 15:08:12 +00005760
John McCall393a78d2012-12-20 02:45:14 +00005761 case Type::ObjCObjectPointer: {
5762 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005763 if (OPT->isObjCIdType()) {
5764 S += '@';
5765 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005766 }
Mike Stump11289f42009-09-09 15:08:12 +00005767
Steve Narofff0c86112009-10-28 22:03:49 +00005768 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5769 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5770 // Since this is a binary compatibility issue, need to consult with runtime
5771 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005772 S += '#';
5773 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005774 }
Mike Stump11289f42009-09-09 15:08:12 +00005775
Chris Lattnere7cabb92009-07-13 00:10:46 +00005776 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005777 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005778 ExpandPointedToStructures,
5779 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005780 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005781 // Note that we do extended encoding of protocol qualifer list
5782 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005783 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005784 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005785 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005786 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005787 S += '>';
5788 }
5789 S += '"';
5790 }
5791 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005792 }
Mike Stump11289f42009-09-09 15:08:12 +00005793
Chris Lattnere7cabb92009-07-13 00:10:46 +00005794 QualType PointeeTy = OPT->getPointeeType();
5795 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005796 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5797 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005798 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005799 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005800 // {...};
5801 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005802 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005803 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005804 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5805 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5806 DeepCollectObjCIvars(OI, true, Ivars);
5807 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5808 if (cast<FieldDecl>(Ivars[i]) == FD) {
5809 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005810 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005811 S += '}';
5812 return;
5813 }
5814 }
5815 }
Mike Stump11289f42009-09-09 15:08:12 +00005816 getObjCEncodingForTypeImpl(PointeeTy, S,
5817 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005818 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005819 false, false, false, false, false,
5820 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005821 return;
5822 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005823
5824 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005825 if (OPT->getInterfaceDecl() &&
5826 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005827 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005828 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005829 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005830 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005831 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005832 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005833 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005834 S += '"';
5835 }
5836 return;
5837 }
Mike Stump11289f42009-09-09 15:08:12 +00005838
John McCalla9e6e8d2010-05-17 23:56:34 +00005839 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005840 // FIXME: we shoul do better than that. 'M' is available.
5841 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005842 // This matches gcc's encoding, even though technically it is insufficient.
5843 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005844 case Type::Vector:
5845 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005846 // Until we have a coherent encoding of these three types, issue warning.
5847 { if (NotEncodedT)
5848 *NotEncodedT = T;
5849 return;
5850 }
5851
5852 // We could see an undeduced auto type here during error recovery.
5853 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005854 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005855 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005856
Richard Smith27d807c2013-04-30 13:56:41 +00005857
John McCall393a78d2012-12-20 02:45:14 +00005858#define ABSTRACT_TYPE(KIND, BASE)
5859#define TYPE(KIND, BASE)
5860#define DEPENDENT_TYPE(KIND, BASE) \
5861 case Type::KIND:
5862#define NON_CANONICAL_TYPE(KIND, BASE) \
5863 case Type::KIND:
5864#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5865 case Type::KIND:
5866#include "clang/AST/TypeNodes.def"
5867 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005868 }
John McCall393a78d2012-12-20 02:45:14 +00005869 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005870}
5871
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005872void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5873 std::string &S,
5874 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005875 bool includeVBases,
5876 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005877 assert(RDecl && "Expected non-null RecordDecl");
5878 assert(!RDecl->isUnion() && "Should not be called for unions");
5879 if (!RDecl->getDefinition())
5880 return;
5881
5882 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5883 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5884 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5885
5886 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005887 for (const auto &BI : CXXRec->bases()) {
5888 if (!BI.isVirtual()) {
5889 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005890 if (base->isEmpty())
5891 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005892 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005893 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5894 std::make_pair(offs, base));
5895 }
5896 }
5897 }
5898
5899 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005900 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005901 uint64_t offs = layout.getFieldOffset(i);
5902 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005903 std::make_pair(offs, Field));
5904 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005905 }
5906
5907 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005908 for (const auto &BI : CXXRec->vbases()) {
5909 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005910 if (base->isEmpty())
5911 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005912 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005913 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5914 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005915 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5916 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005917 }
5918 }
5919
5920 CharUnits size;
5921 if (CXXRec) {
5922 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5923 } else {
5924 size = layout.getSize();
5925 }
5926
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005927#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005928 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005929#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005930 std::multimap<uint64_t, NamedDecl *>::iterator
5931 CurLayObj = FieldOrBaseOffsets.begin();
5932
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005933 if (CXXRec && CXXRec->isDynamicClass() &&
5934 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005935 if (FD) {
5936 S += "\"_vptr$";
5937 std::string recname = CXXRec->getNameAsString();
5938 if (recname.empty()) recname = "?";
5939 S += recname;
5940 S += '"';
5941 }
5942 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005943#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005944 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005945#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005946 }
5947
5948 if (!RDecl->hasFlexibleArrayMember()) {
5949 // Mark the end of the structure.
5950 uint64_t offs = toBits(size);
5951 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00005952 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005953 }
5954
5955 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005956#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005957 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005958 if (CurOffs < CurLayObj->first) {
5959 uint64_t padding = CurLayObj->first - CurOffs;
5960 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5961 // packing/alignment of members is different that normal, in which case
5962 // the encoding will be out-of-sync with the real layout.
5963 // If the runtime switches to just consider the size of types without
5964 // taking into account alignment, we could make padding explicit in the
5965 // encoding (e.g. using arrays of chars). The encoding strings would be
5966 // longer then though.
5967 CurOffs += padding;
5968 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005969#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005970
5971 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00005972 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005973 break; // reached end of structure.
5974
5975 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5976 // We expand the bases without their virtual bases since those are going
5977 // in the initial structure. Note that this differs from gcc which
5978 // expands virtual bases each time one is encountered in the hierarchy,
5979 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005980 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5981 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005982 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005983#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005984 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005985#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005986 } else {
5987 FieldDecl *field = cast<FieldDecl>(dcl);
5988 if (FD) {
5989 S += '"';
5990 S += field->getNameAsString();
5991 S += '"';
5992 }
5993
5994 if (field->isBitField()) {
5995 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005996#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005997 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005998#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005999 } else {
6000 QualType qt = field->getType();
6001 getLegacyIntegralTypeEncoding(qt);
6002 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6003 /*OutermostType*/false,
6004 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006005 /*StructField*/true,
6006 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006007#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006008 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006009#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006010 }
6011 }
6012 }
6013}
6014
Mike Stump11289f42009-09-09 15:08:12 +00006015void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006016 std::string& S) const {
6017 if (QT & Decl::OBJC_TQ_In)
6018 S += 'n';
6019 if (QT & Decl::OBJC_TQ_Inout)
6020 S += 'N';
6021 if (QT & Decl::OBJC_TQ_Out)
6022 S += 'o';
6023 if (QT & Decl::OBJC_TQ_Bycopy)
6024 S += 'O';
6025 if (QT & Decl::OBJC_TQ_Byref)
6026 S += 'R';
6027 if (QT & Decl::OBJC_TQ_Oneway)
6028 S += 'V';
6029}
6030
Douglas Gregor3ea72692011-08-12 05:46:01 +00006031TypedefDecl *ASTContext::getObjCIdDecl() const {
6032 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006033 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006034 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006035 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006036 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006037 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006038}
6039
Douglas Gregor52e02802011-08-12 06:17:30 +00006040TypedefDecl *ASTContext::getObjCSelDecl() const {
6041 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006042 QualType T = getPointerType(ObjCBuiltinSelTy);
6043 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006044 }
6045 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006046}
6047
Douglas Gregor0a586182011-08-12 05:59:41 +00006048TypedefDecl *ASTContext::getObjCClassDecl() const {
6049 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006050 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006051 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006052 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006053 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006054 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006055}
6056
Douglas Gregord53ae832012-01-17 18:09:05 +00006057ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6058 if (!ObjCProtocolClassDecl) {
6059 ObjCProtocolClassDecl
6060 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6061 SourceLocation(),
6062 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006063 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006064 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006065 SourceLocation(), true);
6066 }
6067
6068 return ObjCProtocolClassDecl;
6069}
6070
Meador Inge5d3fb222012-06-16 03:34:49 +00006071//===----------------------------------------------------------------------===//
6072// __builtin_va_list Construction Functions
6073//===----------------------------------------------------------------------===//
6074
Charles Davisc7d5c942015-09-17 20:55:33 +00006075static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6076 StringRef Name) {
6077 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006078 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006079 return Context->buildImplicitTypedef(T, Name);
6080}
6081
6082static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6083 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6084}
6085
6086static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6087 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006088}
6089
6090static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6091 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006092 QualType T = Context->getPointerType(Context->VoidTy);
6093 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006094}
6095
Tim Northover9bb857a2013-01-31 12:13:10 +00006096static TypedefDecl *
6097CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006098 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006099 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006100 if (Context->getLangOpts().CPlusPlus) {
6101 // namespace std { struct __va_list {
6102 NamespaceDecl *NS;
6103 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6104 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006105 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006106 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006107 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006108 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006109 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006110 }
6111
6112 VaListTagDecl->startDefinition();
6113
6114 const size_t NumFields = 5;
6115 QualType FieldTypes[NumFields];
6116 const char *FieldNames[NumFields];
6117
6118 // void *__stack;
6119 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6120 FieldNames[0] = "__stack";
6121
6122 // void *__gr_top;
6123 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6124 FieldNames[1] = "__gr_top";
6125
6126 // void *__vr_top;
6127 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6128 FieldNames[2] = "__vr_top";
6129
6130 // int __gr_offs;
6131 FieldTypes[3] = Context->IntTy;
6132 FieldNames[3] = "__gr_offs";
6133
6134 // int __vr_offs;
6135 FieldTypes[4] = Context->IntTy;
6136 FieldNames[4] = "__vr_offs";
6137
6138 // Create fields
6139 for (unsigned i = 0; i < NumFields; ++i) {
6140 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6141 VaListTagDecl,
6142 SourceLocation(),
6143 SourceLocation(),
6144 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006145 FieldTypes[i], /*TInfo=*/nullptr,
6146 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006147 /*Mutable=*/false,
6148 ICIS_NoInit);
6149 Field->setAccess(AS_public);
6150 VaListTagDecl->addDecl(Field);
6151 }
6152 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006153 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006154 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006155
6156 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006157 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006158}
6159
Meador Inge5d3fb222012-06-16 03:34:49 +00006160static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6161 // typedef struct __va_list_tag {
6162 RecordDecl *VaListTagDecl;
6163
Alp Toker2dea15b2013-12-17 01:22:38 +00006164 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006165 VaListTagDecl->startDefinition();
6166
6167 const size_t NumFields = 5;
6168 QualType FieldTypes[NumFields];
6169 const char *FieldNames[NumFields];
6170
6171 // unsigned char gpr;
6172 FieldTypes[0] = Context->UnsignedCharTy;
6173 FieldNames[0] = "gpr";
6174
6175 // unsigned char fpr;
6176 FieldTypes[1] = Context->UnsignedCharTy;
6177 FieldNames[1] = "fpr";
6178
6179 // unsigned short reserved;
6180 FieldTypes[2] = Context->UnsignedShortTy;
6181 FieldNames[2] = "reserved";
6182
6183 // void* overflow_arg_area;
6184 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6185 FieldNames[3] = "overflow_arg_area";
6186
6187 // void* reg_save_area;
6188 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6189 FieldNames[4] = "reg_save_area";
6190
6191 // Create fields
6192 for (unsigned i = 0; i < NumFields; ++i) {
6193 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6194 SourceLocation(),
6195 SourceLocation(),
6196 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006197 FieldTypes[i], /*TInfo=*/nullptr,
6198 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006199 /*Mutable=*/false,
6200 ICIS_NoInit);
6201 Field->setAccess(AS_public);
6202 VaListTagDecl->addDecl(Field);
6203 }
6204 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006205 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006206 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6207
6208 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006209 TypedefDecl *VaListTagTypedefDecl =
6210 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6211
Meador Inge5d3fb222012-06-16 03:34:49 +00006212 QualType VaListTagTypedefType =
6213 Context->getTypedefType(VaListTagTypedefDecl);
6214
6215 // typedef __va_list_tag __builtin_va_list[1];
6216 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6217 QualType VaListTagArrayType
6218 = Context->getConstantArrayType(VaListTagTypedefType,
6219 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006220 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006221}
6222
6223static TypedefDecl *
6224CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006225 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006226 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006227 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006228 VaListTagDecl->startDefinition();
6229
6230 const size_t NumFields = 4;
6231 QualType FieldTypes[NumFields];
6232 const char *FieldNames[NumFields];
6233
6234 // unsigned gp_offset;
6235 FieldTypes[0] = Context->UnsignedIntTy;
6236 FieldNames[0] = "gp_offset";
6237
6238 // unsigned fp_offset;
6239 FieldTypes[1] = Context->UnsignedIntTy;
6240 FieldNames[1] = "fp_offset";
6241
6242 // void* overflow_arg_area;
6243 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6244 FieldNames[2] = "overflow_arg_area";
6245
6246 // void* reg_save_area;
6247 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6248 FieldNames[3] = "reg_save_area";
6249
6250 // Create fields
6251 for (unsigned i = 0; i < NumFields; ++i) {
6252 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6253 VaListTagDecl,
6254 SourceLocation(),
6255 SourceLocation(),
6256 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006257 FieldTypes[i], /*TInfo=*/nullptr,
6258 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006259 /*Mutable=*/false,
6260 ICIS_NoInit);
6261 Field->setAccess(AS_public);
6262 VaListTagDecl->addDecl(Field);
6263 }
6264 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006265 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006266 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6267
Richard Smith9b88a4c2015-07-27 05:40:23 +00006268 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006269
Richard Smith9b88a4c2015-07-27 05:40:23 +00006270 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006271 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006272 QualType VaListTagArrayType =
6273 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006274 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006275}
6276
6277static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6278 // typedef int __builtin_va_list[4];
6279 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6280 QualType IntArrayType
6281 = Context->getConstantArrayType(Context->IntTy,
6282 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006283 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006284}
6285
Logan Chien57086ce2012-10-10 06:56:20 +00006286static TypedefDecl *
6287CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006288 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006289 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006290 if (Context->getLangOpts().CPlusPlus) {
6291 // namespace std { struct __va_list {
6292 NamespaceDecl *NS;
6293 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6294 Context->getTranslationUnitDecl(),
6295 /*Inline*/false, SourceLocation(),
6296 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006297 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006298 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006299 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006300 }
6301
6302 VaListDecl->startDefinition();
6303
6304 // void * __ap;
6305 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6306 VaListDecl,
6307 SourceLocation(),
6308 SourceLocation(),
6309 &Context->Idents.get("__ap"),
6310 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006311 /*TInfo=*/nullptr,
6312 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006313 /*Mutable=*/false,
6314 ICIS_NoInit);
6315 Field->setAccess(AS_public);
6316 VaListDecl->addDecl(Field);
6317
6318 // };
6319 VaListDecl->completeDefinition();
6320
6321 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006322 QualType T = Context->getRecordType(VaListDecl);
6323 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006324}
6325
Ulrich Weigand47445072013-05-06 16:26:41 +00006326static TypedefDecl *
6327CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006328 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006329 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006330 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006331 VaListTagDecl->startDefinition();
6332
6333 const size_t NumFields = 4;
6334 QualType FieldTypes[NumFields];
6335 const char *FieldNames[NumFields];
6336
6337 // long __gpr;
6338 FieldTypes[0] = Context->LongTy;
6339 FieldNames[0] = "__gpr";
6340
6341 // long __fpr;
6342 FieldTypes[1] = Context->LongTy;
6343 FieldNames[1] = "__fpr";
6344
6345 // void *__overflow_arg_area;
6346 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6347 FieldNames[2] = "__overflow_arg_area";
6348
6349 // void *__reg_save_area;
6350 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6351 FieldNames[3] = "__reg_save_area";
6352
6353 // Create fields
6354 for (unsigned i = 0; i < NumFields; ++i) {
6355 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6356 VaListTagDecl,
6357 SourceLocation(),
6358 SourceLocation(),
6359 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006360 FieldTypes[i], /*TInfo=*/nullptr,
6361 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006362 /*Mutable=*/false,
6363 ICIS_NoInit);
6364 Field->setAccess(AS_public);
6365 VaListTagDecl->addDecl(Field);
6366 }
6367 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006368 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006369 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006370
Richard Smith9b88a4c2015-07-27 05:40:23 +00006371 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006372
6373 // typedef __va_list_tag __builtin_va_list[1];
6374 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006375 QualType VaListTagArrayType =
6376 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006377
Alp Toker56b5cc92013-12-15 10:36:26 +00006378 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006379}
6380
Meador Inge5d3fb222012-06-16 03:34:49 +00006381static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6382 TargetInfo::BuiltinVaListKind Kind) {
6383 switch (Kind) {
6384 case TargetInfo::CharPtrBuiltinVaList:
6385 return CreateCharPtrBuiltinVaListDecl(Context);
6386 case TargetInfo::VoidPtrBuiltinVaList:
6387 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006388 case TargetInfo::AArch64ABIBuiltinVaList:
6389 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006390 case TargetInfo::PowerABIBuiltinVaList:
6391 return CreatePowerABIBuiltinVaListDecl(Context);
6392 case TargetInfo::X86_64ABIBuiltinVaList:
6393 return CreateX86_64ABIBuiltinVaListDecl(Context);
6394 case TargetInfo::PNaClABIBuiltinVaList:
6395 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006396 case TargetInfo::AAPCSABIBuiltinVaList:
6397 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006398 case TargetInfo::SystemZBuiltinVaList:
6399 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006400 }
6401
6402 llvm_unreachable("Unhandled __builtin_va_list type kind");
6403}
6404
6405TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006406 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006407 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006408 assert(BuiltinVaListDecl->isImplicit());
6409 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006410
6411 return BuiltinVaListDecl;
6412}
6413
Richard Smith9b88a4c2015-07-27 05:40:23 +00006414Decl *ASTContext::getVaListTagDecl() const {
6415 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006416 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006417 if (!VaListTagDecl)
6418 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006419
Richard Smith9b88a4c2015-07-27 05:40:23 +00006420 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006421}
6422
Charles Davisc7d5c942015-09-17 20:55:33 +00006423TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6424 if (!BuiltinMSVaListDecl)
6425 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6426
6427 return BuiltinMSVaListDecl;
6428}
6429
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006430void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006431 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006432 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006433
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006434 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006435}
6436
John McCalld28ae272009-12-02 08:04:21 +00006437/// \brief Retrieve the template name that corresponds to a non-empty
6438/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006439TemplateName
6440ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6441 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006442 unsigned size = End - Begin;
6443 assert(size > 1 && "set is not overloaded!");
6444
6445 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6446 size * sizeof(FunctionTemplateDecl*));
6447 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6448
6449 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006450 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006451 NamedDecl *D = *I;
6452 assert(isa<FunctionTemplateDecl>(D) ||
6453 (isa<UsingShadowDecl>(D) &&
6454 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6455 *Storage++ = D;
6456 }
6457
6458 return TemplateName(OT);
6459}
6460
Douglas Gregordc572a32009-03-30 22:58:21 +00006461/// \brief Retrieve the template name that represents a qualified
6462/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006463TemplateName
6464ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6465 bool TemplateKeyword,
6466 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006467 assert(NNS && "Missing nested-name-specifier in qualified template name");
6468
Douglas Gregorc42075a2010-02-04 18:10:26 +00006469 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006470 llvm::FoldingSetNodeID ID;
6471 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6472
Craig Topper36250ad2014-05-12 05:36:57 +00006473 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006474 QualifiedTemplateName *QTN =
6475 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6476 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006477 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6478 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006479 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6480 }
6481
6482 return TemplateName(QTN);
6483}
6484
6485/// \brief Retrieve the template name that represents a dependent
6486/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006487TemplateName
6488ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6489 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006490 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006491 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006492
6493 llvm::FoldingSetNodeID ID;
6494 DependentTemplateName::Profile(ID, NNS, Name);
6495
Craig Topper36250ad2014-05-12 05:36:57 +00006496 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006497 DependentTemplateName *QTN =
6498 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6499
6500 if (QTN)
6501 return TemplateName(QTN);
6502
6503 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6504 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006505 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6506 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006507 } else {
6508 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006509 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6510 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006511 DependentTemplateName *CheckQTN =
6512 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6513 assert(!CheckQTN && "Dependent type name canonicalization broken");
6514 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006515 }
6516
6517 DependentTemplateNames.InsertNode(QTN, InsertPos);
6518 return TemplateName(QTN);
6519}
6520
Douglas Gregor71395fa2009-11-04 00:56:37 +00006521/// \brief Retrieve the template name that represents a dependent
6522/// template name such as \c MetaFun::template operator+.
6523TemplateName
6524ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006525 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006526 assert((!NNS || NNS->isDependent()) &&
6527 "Nested name specifier must be dependent");
6528
6529 llvm::FoldingSetNodeID ID;
6530 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006531
6532 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006533 DependentTemplateName *QTN
6534 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006535
6536 if (QTN)
6537 return TemplateName(QTN);
6538
6539 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6540 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006541 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6542 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006543 } else {
6544 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006545 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6546 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006547
6548 DependentTemplateName *CheckQTN
6549 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6550 assert(!CheckQTN && "Dependent template name canonicalization broken");
6551 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006552 }
6553
6554 DependentTemplateNames.InsertNode(QTN, InsertPos);
6555 return TemplateName(QTN);
6556}
6557
Douglas Gregor5590be02011-01-15 06:45:20 +00006558TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006559ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6560 TemplateName replacement) const {
6561 llvm::FoldingSetNodeID ID;
6562 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006563
6564 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006565 SubstTemplateTemplateParmStorage *subst
6566 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6567
6568 if (!subst) {
6569 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6570 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6571 }
6572
6573 return TemplateName(subst);
6574}
6575
6576TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006577ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6578 const TemplateArgument &ArgPack) const {
6579 ASTContext &Self = const_cast<ASTContext &>(*this);
6580 llvm::FoldingSetNodeID ID;
6581 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006582
6583 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006584 SubstTemplateTemplateParmPackStorage *Subst
6585 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6586
6587 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006588 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006589 ArgPack.pack_size(),
6590 ArgPack.pack_begin());
6591 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6592 }
6593
6594 return TemplateName(Subst);
6595}
6596
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006597/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006598/// TargetInfo, produce the corresponding type. The unsigned @p Type
6599/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006600CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006601 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006602 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006603 case TargetInfo::SignedChar: return SignedCharTy;
6604 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006605 case TargetInfo::SignedShort: return ShortTy;
6606 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6607 case TargetInfo::SignedInt: return IntTy;
6608 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6609 case TargetInfo::SignedLong: return LongTy;
6610 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6611 case TargetInfo::SignedLongLong: return LongLongTy;
6612 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6613 }
6614
David Blaikie83d382b2011-09-23 05:06:16 +00006615 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006616}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006617
6618//===----------------------------------------------------------------------===//
6619// Type Predicates.
6620//===----------------------------------------------------------------------===//
6621
Fariborz Jahanian96207692009-02-18 21:49:28 +00006622/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6623/// garbage collection attribute.
6624///
John McCall553d45a2011-01-12 00:34:59 +00006625Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006626 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006627 return Qualifiers::GCNone;
6628
David Blaikiebbafb8a2012-03-11 07:00:24 +00006629 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006630 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6631
6632 // Default behaviour under objective-C's gc is for ObjC pointers
6633 // (or pointers to them) be treated as though they were declared
6634 // as __strong.
6635 if (GCAttrs == Qualifiers::GCNone) {
6636 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6637 return Qualifiers::Strong;
6638 else if (Ty->isPointerType())
6639 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6640 } else {
6641 // It's not valid to set GC attributes on anything that isn't a
6642 // pointer.
6643#ifndef NDEBUG
6644 QualType CT = Ty->getCanonicalTypeInternal();
6645 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6646 CT = AT->getElementType();
6647 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6648#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006649 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006650 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006651}
6652
Chris Lattner49af6a42008-04-07 06:51:04 +00006653//===----------------------------------------------------------------------===//
6654// Type Compatibility Testing
6655//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006656
Mike Stump11289f42009-09-09 15:08:12 +00006657/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006658/// compatible.
6659static bool areCompatVectorTypes(const VectorType *LHS,
6660 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006661 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006662 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006663 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006664}
6665
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006666bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6667 QualType SecondVec) {
6668 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6669 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6670
6671 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6672 return true;
6673
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006674 // Treat Neon vector types and most AltiVec vector types as if they are the
6675 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006676 const VectorType *First = FirstVec->getAs<VectorType>();
6677 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006678 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006679 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006680 First->getVectorKind() != VectorType::AltiVecPixel &&
6681 First->getVectorKind() != VectorType::AltiVecBool &&
6682 Second->getVectorKind() != VectorType::AltiVecPixel &&
6683 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006684 return true;
6685
6686 return false;
6687}
6688
Steve Naroff8e6aee52009-07-23 01:01:38 +00006689//===----------------------------------------------------------------------===//
6690// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6691//===----------------------------------------------------------------------===//
6692
6693/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6694/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006695bool
6696ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6697 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006698 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006699 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006700 for (auto *PI : rProto->protocols())
6701 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006702 return true;
6703 return false;
6704}
6705
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006706/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6707/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006708bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6709 QualType rhs) {
6710 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6711 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6712 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6713
Aaron Ballman83731462014-03-17 16:14:00 +00006714 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006715 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006716 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006717 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6718 match = true;
6719 break;
6720 }
6721 }
6722 if (!match)
6723 return false;
6724 }
6725 return true;
6726}
6727
Steve Naroff8e6aee52009-07-23 01:01:38 +00006728/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6729/// ObjCQualifiedIDType.
6730bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6731 bool compare) {
6732 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006733 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006734 lhs->isObjCIdType() || lhs->isObjCClassType())
6735 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006736 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006737 rhs->isObjCIdType() || rhs->isObjCClassType())
6738 return true;
6739
6740 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006741 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006742
Steve Naroff8e6aee52009-07-23 01:01:38 +00006743 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006744
Steve Naroff8e6aee52009-07-23 01:01:38 +00006745 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006746 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006747 // make sure we check the class hierarchy.
6748 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006749 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006750 // when comparing an id<P> on lhs with a static type on rhs,
6751 // see if static class implements all of id's protocols, directly or
6752 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006753 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006754 return false;
6755 }
6756 }
6757 // If there are no qualifiers and no interface, we have an 'id'.
6758 return true;
6759 }
Mike Stump11289f42009-09-09 15:08:12 +00006760 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006761 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006762 bool match = false;
6763
6764 // when comparing an id<P> on lhs with a static type on rhs,
6765 // see if static class implements all of id's protocols, directly or
6766 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006767 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006768 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6769 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6770 match = true;
6771 break;
6772 }
6773 }
Mike Stump11289f42009-09-09 15:08:12 +00006774 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006775 // make sure we check the class hierarchy.
6776 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006777 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006778 // when comparing an id<P> on lhs with a static type on rhs,
6779 // see if static class implements all of id's protocols, directly or
6780 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006781 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006782 match = true;
6783 break;
6784 }
6785 }
6786 }
6787 if (!match)
6788 return false;
6789 }
Mike Stump11289f42009-09-09 15:08:12 +00006790
Steve Naroff8e6aee52009-07-23 01:01:38 +00006791 return true;
6792 }
Mike Stump11289f42009-09-09 15:08:12 +00006793
Steve Naroff8e6aee52009-07-23 01:01:38 +00006794 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6795 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6796
Mike Stump11289f42009-09-09 15:08:12 +00006797 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006798 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006799 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006800 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006801 bool match = false;
6802
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006803 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006804 // see if static class implements all of id's protocols, directly or
6805 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006806 // First, lhs protocols in the qualifier list must be found, direct
6807 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006808 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006809 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6810 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6811 match = true;
6812 break;
6813 }
6814 }
6815 if (!match)
6816 return false;
6817 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006818
6819 // Static class's protocols, or its super class or category protocols
6820 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6821 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6822 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6823 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6824 // This is rather dubious but matches gcc's behavior. If lhs has
6825 // no type qualifier and its class has no static protocol(s)
6826 // assume that it is mismatch.
6827 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6828 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006829 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006830 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006831 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006832 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6833 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6834 match = true;
6835 break;
6836 }
6837 }
6838 if (!match)
6839 return false;
6840 }
6841 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006842 return true;
6843 }
6844 return false;
6845}
6846
Eli Friedman47f77112008-08-22 00:56:42 +00006847/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006848/// compatible for assignment from RHS to LHS. This handles validation of any
6849/// protocol qualifiers on the LHS or RHS.
6850///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006851bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6852 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006853 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6854 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6855
Steve Naroff1329fa02009-07-15 18:40:39 +00006856 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006857 if (LHS->isObjCUnqualifiedIdOrClass() ||
6858 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006859 return true;
6860
Douglas Gregorab209d82015-07-07 03:58:42 +00006861 // Function object that propagates a successful result or handles
6862 // __kindof types.
6863 auto finish = [&](bool succeeded) -> bool {
6864 if (succeeded)
6865 return true;
6866
6867 if (!RHS->isKindOfType())
6868 return false;
6869
6870 // Strip off __kindof and protocol qualifiers, then check whether
6871 // we can assign the other way.
6872 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6873 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6874 };
6875
6876 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6877 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6878 QualType(RHSOPT,0),
6879 false));
6880 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006881
Douglas Gregorab209d82015-07-07 03:58:42 +00006882 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6883 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6884 QualType(RHSOPT,0)));
6885 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006886
John McCall8b07ec22010-05-15 11:32:37 +00006887 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006888 if (LHS->getInterface() && RHS->getInterface()) {
6889 return finish(canAssignObjCInterfaces(LHS, RHS));
6890 }
Mike Stump11289f42009-09-09 15:08:12 +00006891
Steve Naroff8e6aee52009-07-23 01:01:38 +00006892 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006893}
6894
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006895/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006896/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006897/// arguments in block literals. When passed as arguments, passing 'A*' where
6898/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6899/// not OK. For the return type, the opposite is not OK.
6900bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6901 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006902 const ObjCObjectPointerType *RHSOPT,
6903 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006904
6905 // Function object that propagates a successful result or handles
6906 // __kindof types.
6907 auto finish = [&](bool succeeded) -> bool {
6908 if (succeeded)
6909 return true;
6910
6911 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6912 if (!Expected->isKindOfType())
6913 return false;
6914
6915 // Strip off __kindof and protocol qualifiers, then check whether
6916 // we can assign the other way.
6917 return canAssignObjCInterfacesInBlockPointer(
6918 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6919 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6920 BlockReturnType);
6921 };
6922
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006923 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006924 return true;
6925
6926 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006927 return finish(RHSOPT->isObjCBuiltinType() ||
6928 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006929 }
6930
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006931 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00006932 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6933 QualType(RHSOPT,0),
6934 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006935
6936 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6937 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6938 if (LHS && RHS) { // We have 2 user-defined types.
6939 if (LHS != RHS) {
6940 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006941 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006942 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00006943 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006944 }
6945 else
6946 return true;
6947 }
6948 return false;
6949}
6950
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006951/// Comparison routine for Objective-C protocols to be used with
6952/// llvm::array_pod_sort.
6953static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6954 ObjCProtocolDecl * const *rhs) {
6955 return (*lhs)->getName().compare((*rhs)->getName());
6956
6957}
6958
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006959/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006960/// of protocols inherited from two distinct objective-c pointer objects with
6961/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006962/// It is used to build composite qualifier list of the composite type of
6963/// the conditional expression involving two objective-c pointer objects.
6964static
6965void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006966 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006967 const ObjCObjectPointerType *LHSOPT,
6968 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006969 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006970
John McCall8b07ec22010-05-15 11:32:37 +00006971 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6972 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6973 assert(LHS->getInterface() && "LHS must have an interface base");
6974 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006975
6976 // Add all of the protocols for the LHS.
6977 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6978
6979 // Start with the protocol qualifiers.
6980 for (auto proto : LHS->quals()) {
6981 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006982 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006983
6984 // Also add the protocols associated with the LHS interface.
6985 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6986
6987 // Add all of the protocls for the RHS.
6988 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6989
6990 // Start with the protocol qualifiers.
6991 for (auto proto : RHS->quals()) {
6992 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006993 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006994
6995 // Also add the protocols associated with the RHS interface.
6996 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6997
6998 // Compute the intersection of the collected protocol sets.
6999 for (auto proto : LHSProtocolSet) {
7000 if (RHSProtocolSet.count(proto))
7001 IntersectionSet.push_back(proto);
7002 }
7003
7004 // Compute the set of protocols that is implied by either the common type or
7005 // the protocols within the intersection.
7006 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7007 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7008
7009 // Remove any implied protocols from the list of inherited protocols.
7010 if (!ImpliedProtocols.empty()) {
7011 IntersectionSet.erase(
7012 std::remove_if(IntersectionSet.begin(),
7013 IntersectionSet.end(),
7014 [&](ObjCProtocolDecl *proto) -> bool {
7015 return ImpliedProtocols.count(proto) > 0;
7016 }),
7017 IntersectionSet.end());
7018 }
7019
7020 // Sort the remaining protocols by name.
7021 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7022 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007023}
7024
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007025/// Determine whether the first type is a subtype of the second.
7026static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7027 QualType rhs) {
7028 // Common case: two object pointers.
7029 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7030 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7031 if (lhsOPT && rhsOPT)
7032 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7033
7034 // Two block pointers.
7035 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7036 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7037 if (lhsBlock && rhsBlock)
7038 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7039
7040 // If either is an unqualified 'id' and the other is a block, it's
7041 // acceptable.
7042 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7043 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7044 return true;
7045
7046 return false;
7047}
7048
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007049// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007050static bool sameObjCTypeArgs(ASTContext &ctx,
7051 const ObjCInterfaceDecl *iface,
7052 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007053 ArrayRef<QualType> rhsArgs,
7054 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007055 if (lhsArgs.size() != rhsArgs.size())
7056 return false;
7057
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007058 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007059 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007060 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7061 continue;
7062
7063 switch (typeParams->begin()[i]->getVariance()) {
7064 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007065 if (!stripKindOf ||
7066 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7067 rhsArgs[i].stripObjCKindOfType(ctx))) {
7068 return false;
7069 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007070 break;
7071
7072 case ObjCTypeParamVariance::Covariant:
7073 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7074 return false;
7075 break;
7076
7077 case ObjCTypeParamVariance::Contravariant:
7078 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7079 return false;
7080 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007081 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007082 }
7083
7084 return true;
7085}
7086
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007087QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007088 const ObjCObjectPointerType *Lptr,
7089 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007090 const ObjCObjectType *LHS = Lptr->getObjectType();
7091 const ObjCObjectType *RHS = Rptr->getObjectType();
7092 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7093 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007094
7095 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007096 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007097
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007098 // Follow the left-hand side up the class hierarchy until we either hit a
7099 // root or find the RHS. Record the ancestors in case we don't find it.
7100 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7101 LHSAncestors;
7102 while (true) {
7103 // Record this ancestor. We'll need this if the common type isn't in the
7104 // path from the LHS to the root.
7105 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007106
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007107 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7108 // Get the type arguments.
7109 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7110 bool anyChanges = false;
7111 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7112 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007113 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7114 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007115 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007116 return QualType();
7117 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7118 // If only one has type arguments, the result will not have type
7119 // arguments.
7120 LHSTypeArgs = { };
7121 anyChanges = true;
7122 }
7123
7124 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007125 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007126 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7127 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007128 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007129 anyChanges = true;
7130
7131 // If anything in the LHS will have changed, build a new result type.
7132 if (anyChanges) {
7133 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007134 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7135 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007136 return getObjCObjectPointerType(Result);
7137 }
7138
7139 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007140 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007141
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007142 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007143 QualType LHSSuperType = LHS->getSuperClassType();
7144 if (LHSSuperType.isNull())
7145 break;
7146
7147 LHS = LHSSuperType->castAs<ObjCObjectType>();
7148 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007149
7150 // We didn't find anything by following the LHS to its root; now check
7151 // the RHS against the cached set of ancestors.
7152 while (true) {
7153 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7154 if (KnownLHS != LHSAncestors.end()) {
7155 LHS = KnownLHS->second;
7156
7157 // Get the type arguments.
7158 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7159 bool anyChanges = false;
7160 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7161 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007162 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7163 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007164 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007165 return QualType();
7166 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7167 // If only one has type arguments, the result will not have type
7168 // arguments.
7169 RHSTypeArgs = { };
7170 anyChanges = true;
7171 }
7172
7173 // Compute the intersection of protocols.
7174 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7175 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7176 Protocols);
7177 if (!Protocols.empty())
7178 anyChanges = true;
7179
7180 if (anyChanges) {
7181 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007182 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7183 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007184 return getObjCObjectPointerType(Result);
7185 }
7186
7187 return getObjCObjectPointerType(QualType(RHS, 0));
7188 }
7189
7190 // Find the superclass of the RHS.
7191 QualType RHSSuperType = RHS->getSuperClassType();
7192 if (RHSSuperType.isNull())
7193 break;
7194
7195 RHS = RHSSuperType->castAs<ObjCObjectType>();
7196 }
7197
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007198 return QualType();
7199}
7200
John McCall8b07ec22010-05-15 11:32:37 +00007201bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7202 const ObjCObjectType *RHS) {
7203 assert(LHS->getInterface() && "LHS is not an interface type");
7204 assert(RHS->getInterface() && "RHS is not an interface type");
7205
Chris Lattner49af6a42008-04-07 06:51:04 +00007206 // Verify that the base decls are compatible: the RHS must be a subclass of
7207 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007208 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7209 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7210 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007211 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007212
Douglas Gregore83b9562015-07-07 03:57:53 +00007213 // If the LHS has protocol qualifiers, determine whether all of them are
7214 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7215 // LHS).
7216 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007217 // OK if conversion of LHS to SuperClass results in narrowing of types
7218 // ; i.e., SuperClass may implement at least one of the protocols
7219 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7220 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7221 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7222 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7223 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7224 // qualifiers.
7225 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007226 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007227 // If there is no protocols associated with RHS, it is not a match.
7228 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007229 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007230
7231 for (const auto *LHSProto : LHS->quals()) {
7232 bool SuperImplementsProtocol = false;
7233 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7234 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7235 SuperImplementsProtocol = true;
7236 break;
7237 }
7238 if (!SuperImplementsProtocol)
7239 return false;
7240 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007241 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007242
7243 // If the LHS is specialized, we may need to check type arguments.
7244 if (LHS->isSpecialized()) {
7245 // Follow the superclass chain until we've matched the LHS class in the
7246 // hierarchy. This substitutes type arguments through.
7247 const ObjCObjectType *RHSSuper = RHS;
7248 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7249 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7250
7251 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007252 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007253 !sameObjCTypeArgs(*this, LHS->getInterface(),
7254 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007255 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007256 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007257 }
7258 }
7259
7260 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007261}
7262
Steve Naroffb7605152009-02-12 17:52:19 +00007263bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7264 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007265 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7266 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007267
Steve Naroff7cae42b2009-07-10 23:34:53 +00007268 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007269 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007270
7271 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7272 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007273}
7274
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007275bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7276 return canAssignObjCInterfaces(
7277 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7278 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7279}
7280
Mike Stump11289f42009-09-09 15:08:12 +00007281/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007282/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007283/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007284/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007285bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7286 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007287 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007288 return hasSameType(LHS, RHS);
7289
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007290 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007291}
7292
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007293bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007294 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007295}
7296
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007297bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7298 return !mergeTypes(LHS, RHS, true).isNull();
7299}
7300
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007301/// mergeTransparentUnionType - if T is a transparent union type and a member
7302/// of T is compatible with SubType, return the merged type, else return
7303/// QualType()
7304QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7305 bool OfBlockPointer,
7306 bool Unqualified) {
7307 if (const RecordType *UT = T->getAsUnionType()) {
7308 RecordDecl *UD = UT->getDecl();
7309 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007310 for (const auto *I : UD->fields()) {
7311 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007312 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7313 if (!MT.isNull())
7314 return MT;
7315 }
7316 }
7317 }
7318
7319 return QualType();
7320}
7321
Alp Toker9cacbab2014-01-20 20:26:09 +00007322/// mergeFunctionParameterTypes - merge two types which appear as function
7323/// parameter types
7324QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7325 bool OfBlockPointer,
7326 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007327 // GNU extension: two types are compatible if they appear as a function
7328 // argument, one of the types is a transparent union type and the other
7329 // type is compatible with a union member
7330 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7331 Unqualified);
7332 if (!lmerge.isNull())
7333 return lmerge;
7334
7335 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7336 Unqualified);
7337 if (!rmerge.isNull())
7338 return rmerge;
7339
7340 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7341}
7342
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007343QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007344 bool OfBlockPointer,
7345 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007346 const FunctionType *lbase = lhs->getAs<FunctionType>();
7347 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007348 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7349 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007350 bool allLTypes = true;
7351 bool allRTypes = true;
7352
7353 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007354 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007355 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007356 QualType RHS = rbase->getReturnType();
7357 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007358 bool UnqualifiedResult = Unqualified;
7359 if (!UnqualifiedResult)
7360 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007361 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007362 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007363 else
Alp Toker314cc812014-01-25 16:55:45 +00007364 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007365 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007366 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007367
7368 if (Unqualified)
7369 retType = retType.getUnqualifiedType();
7370
Alp Toker314cc812014-01-25 16:55:45 +00007371 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7372 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007373 if (Unqualified) {
7374 LRetType = LRetType.getUnqualifiedType();
7375 RRetType = RRetType.getUnqualifiedType();
7376 }
7377
7378 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007379 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007380 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007381 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007382
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007383 // FIXME: double check this
7384 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7385 // rbase->getRegParmAttr() != 0 &&
7386 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007387 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7388 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007389
Douglas Gregor8c940862010-01-18 17:14:39 +00007390 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007391 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007392 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007393
John McCall8c6b56f2010-12-15 01:06:38 +00007394 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007395 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7396 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007397 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7398 return QualType();
7399
John McCall31168b02011-06-15 23:02:42 +00007400 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7401 return QualType();
7402
John McCall8c6b56f2010-12-15 01:06:38 +00007403 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7404 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007405
Rafael Espindola8778c282012-11-29 16:09:03 +00007406 if (lbaseInfo.getNoReturn() != NoReturn)
7407 allLTypes = false;
7408 if (rbaseInfo.getNoReturn() != NoReturn)
7409 allRTypes = false;
7410
John McCall31168b02011-06-15 23:02:42 +00007411 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007412
Eli Friedman47f77112008-08-22 00:56:42 +00007413 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007414 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7415 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007416 // Compatible functions must have the same number of parameters
7417 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007418 return QualType();
7419
7420 // Variadic and non-variadic functions aren't compatible
7421 if (lproto->isVariadic() != rproto->isVariadic())
7422 return QualType();
7423
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007424 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7425 return QualType();
7426
Fariborz Jahanian97676972011-09-28 21:52:05 +00007427 if (LangOpts.ObjCAutoRefCount &&
7428 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7429 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007430
7431 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007432 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007433 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7434 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7435 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7436 QualType paramType = mergeFunctionParameterTypes(
7437 lParamType, rParamType, OfBlockPointer, Unqualified);
7438 if (paramType.isNull())
7439 return QualType();
7440
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007441 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007442 paramType = paramType.getUnqualifiedType();
7443
7444 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007445 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007446 lParamType = lParamType.getUnqualifiedType();
7447 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007448 }
Alp Toker601b22c2014-01-21 23:35:24 +00007449
7450 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007451 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007452 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007453 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007454 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007455
Eli Friedman47f77112008-08-22 00:56:42 +00007456 if (allLTypes) return lhs;
7457 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007458
7459 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7460 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007461 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007462 }
7463
7464 if (lproto) allRTypes = false;
7465 if (rproto) allLTypes = false;
7466
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007467 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007468 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007469 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007470 if (proto->isVariadic()) return QualType();
7471 // Check that the types are compatible with the types that
7472 // would result from default argument promotions (C99 6.7.5.3p15).
7473 // The only types actually affected are promotable integer
7474 // types and floats, which would be passed as a different
7475 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007476 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7477 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007478
Eli Friedman448ce402012-08-30 00:44:15 +00007479 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007480 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007481 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7482 paramTy = Enum->getDecl()->getIntegerType();
7483 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007484 return QualType();
7485 }
Alp Toker601b22c2014-01-21 23:35:24 +00007486
7487 if (paramTy->isPromotableIntegerType() ||
7488 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007489 return QualType();
7490 }
7491
7492 if (allLTypes) return lhs;
7493 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007494
7495 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7496 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007497 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007498 }
7499
7500 if (allLTypes) return lhs;
7501 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007502 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007503}
7504
John McCall433c2e62013-03-21 00:10:07 +00007505/// Given that we have an enum type and a non-enum type, try to merge them.
7506static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7507 QualType other, bool isBlockReturnType) {
7508 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7509 // a signed integer type, or an unsigned integer type.
7510 // Compatibility is based on the underlying type, not the promotion
7511 // type.
7512 QualType underlyingType = ET->getDecl()->getIntegerType();
7513 if (underlyingType.isNull()) return QualType();
7514 if (Context.hasSameType(underlyingType, other))
7515 return other;
7516
7517 // In block return types, we're more permissive and accept any
7518 // integral type of the same size.
7519 if (isBlockReturnType && other->isIntegerType() &&
7520 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7521 return other;
7522
7523 return QualType();
7524}
7525
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007526QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007527 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007528 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007529 // C++ [expr]: If an expression initially has the type "reference to T", the
7530 // type is adjusted to "T" prior to any further analysis, the expression
7531 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007532 // expression is an lvalue unless the reference is an rvalue reference and
7533 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007534 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7535 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007536
7537 if (Unqualified) {
7538 LHS = LHS.getUnqualifiedType();
7539 RHS = RHS.getUnqualifiedType();
7540 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007541
Eli Friedman47f77112008-08-22 00:56:42 +00007542 QualType LHSCan = getCanonicalType(LHS),
7543 RHSCan = getCanonicalType(RHS);
7544
7545 // If two types are identical, they are compatible.
7546 if (LHSCan == RHSCan)
7547 return LHS;
7548
John McCall8ccfcb52009-09-24 19:53:00 +00007549 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007550 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7551 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007552 if (LQuals != RQuals) {
7553 // If any of these qualifiers are different, we have a type
7554 // mismatch.
7555 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007556 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7557 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007558 return QualType();
7559
7560 // Exactly one GC qualifier difference is allowed: __strong is
7561 // okay if the other type has no GC qualifier but is an Objective
7562 // C object pointer (i.e. implicitly strong by default). We fix
7563 // this by pretending that the unqualified type was actually
7564 // qualified __strong.
7565 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7566 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7567 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7568
7569 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7570 return QualType();
7571
7572 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7573 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7574 }
7575 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7576 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7577 }
Eli Friedman47f77112008-08-22 00:56:42 +00007578 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007579 }
7580
7581 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007582
Eli Friedmandcca6332009-06-01 01:22:52 +00007583 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7584 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007585
Chris Lattnerfd652912008-01-14 05:45:46 +00007586 // We want to consider the two function types to be the same for these
7587 // comparisons, just force one to the other.
7588 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7589 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007590
7591 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007592 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7593 LHSClass = Type::ConstantArray;
7594 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7595 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007596
John McCall8b07ec22010-05-15 11:32:37 +00007597 // ObjCInterfaces are just specialized ObjCObjects.
7598 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7599 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7600
Nate Begemance4d7fc2008-04-18 23:10:10 +00007601 // Canonicalize ExtVector -> Vector.
7602 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7603 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007604
Chris Lattner95554662008-04-07 05:43:21 +00007605 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007606 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007607 // Note that we only have special rules for turning block enum
7608 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007609 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007610 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007611 }
John McCall9dd450b2009-09-21 23:43:11 +00007612 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007613 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007614 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007615 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007616 if (OfBlockPointer && !BlockReturnType) {
7617 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7618 return LHS;
7619 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7620 return RHS;
7621 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007622
Eli Friedman47f77112008-08-22 00:56:42 +00007623 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007624 }
Eli Friedman47f77112008-08-22 00:56:42 +00007625
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007626 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007627 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007628#define TYPE(Class, Base)
7629#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007630#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007631#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7632#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7633#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007634 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007635
Richard Smith27d807c2013-04-30 13:56:41 +00007636 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007637 case Type::LValueReference:
7638 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007639 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007640 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007641
John McCall8b07ec22010-05-15 11:32:37 +00007642 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007643 case Type::IncompleteArray:
7644 case Type::VariableArray:
7645 case Type::FunctionProto:
7646 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007647 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007648
Chris Lattnerfd652912008-01-14 05:45:46 +00007649 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007650 {
7651 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007652 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7653 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007654 if (Unqualified) {
7655 LHSPointee = LHSPointee.getUnqualifiedType();
7656 RHSPointee = RHSPointee.getUnqualifiedType();
7657 }
7658 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7659 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007660 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007661 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007662 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007663 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007664 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007665 return getPointerType(ResultType);
7666 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007667 case Type::BlockPointer:
7668 {
7669 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007670 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7671 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007672 if (Unqualified) {
7673 LHSPointee = LHSPointee.getUnqualifiedType();
7674 RHSPointee = RHSPointee.getUnqualifiedType();
7675 }
7676 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7677 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007678 if (ResultType.isNull()) return QualType();
7679 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7680 return LHS;
7681 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7682 return RHS;
7683 return getBlockPointerType(ResultType);
7684 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007685 case Type::Atomic:
7686 {
7687 // Merge two pointer types, while trying to preserve typedef info
7688 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7689 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7690 if (Unqualified) {
7691 LHSValue = LHSValue.getUnqualifiedType();
7692 RHSValue = RHSValue.getUnqualifiedType();
7693 }
7694 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7695 Unqualified);
7696 if (ResultType.isNull()) return QualType();
7697 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7698 return LHS;
7699 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7700 return RHS;
7701 return getAtomicType(ResultType);
7702 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007703 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007704 {
7705 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7706 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7707 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7708 return QualType();
7709
7710 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7711 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007712 if (Unqualified) {
7713 LHSElem = LHSElem.getUnqualifiedType();
7714 RHSElem = RHSElem.getUnqualifiedType();
7715 }
7716
7717 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007718 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007719 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7720 return LHS;
7721 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7722 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007723 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7724 ArrayType::ArraySizeModifier(), 0);
7725 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7726 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007727 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7728 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007729 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7730 return LHS;
7731 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7732 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007733 if (LVAT) {
7734 // FIXME: This isn't correct! But tricky to implement because
7735 // the array's size has to be the size of LHS, but the type
7736 // has to be different.
7737 return LHS;
7738 }
7739 if (RVAT) {
7740 // FIXME: This isn't correct! But tricky to implement because
7741 // the array's size has to be the size of RHS, but the type
7742 // has to be different.
7743 return RHS;
7744 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007745 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7746 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007747 return getIncompleteArrayType(ResultType,
7748 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007749 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007750 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007751 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007752 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007753 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007754 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007755 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007756 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007757 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007758 case Type::Complex:
7759 // Distinct complex types are incompatible.
7760 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007761 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007762 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007763 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7764 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007765 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007766 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007767 case Type::ObjCObject: {
7768 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007769 // FIXME: This should be type compatibility, e.g. whether
7770 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007771 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7772 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7773 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007774 return LHS;
7775
Eli Friedman47f77112008-08-22 00:56:42 +00007776 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007777 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007778 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007779 if (OfBlockPointer) {
7780 if (canAssignObjCInterfacesInBlockPointer(
7781 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007782 RHS->getAs<ObjCObjectPointerType>(),
7783 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007784 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007785 return QualType();
7786 }
John McCall9dd450b2009-09-21 23:43:11 +00007787 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7788 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007789 return LHS;
7790
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007791 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007792 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007793 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007794
David Blaikie8a40f702012-01-17 06:56:22 +00007795 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007796}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007797
Fariborz Jahanian97676972011-09-28 21:52:05 +00007798bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7799 const FunctionProtoType *FromFunctionType,
7800 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007801 if (FromFunctionType->hasAnyConsumedParams() !=
7802 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007803 return false;
7804 FunctionProtoType::ExtProtoInfo FromEPI =
7805 FromFunctionType->getExtProtoInfo();
7806 FunctionProtoType::ExtProtoInfo ToEPI =
7807 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007808 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007809 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7810 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007811 return false;
7812 }
7813 return true;
7814}
7815
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007816/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7817/// 'RHS' attributes and returns the merged version; including for function
7818/// return types.
7819QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7820 QualType LHSCan = getCanonicalType(LHS),
7821 RHSCan = getCanonicalType(RHS);
7822 // If two types are identical, they are compatible.
7823 if (LHSCan == RHSCan)
7824 return LHS;
7825 if (RHSCan->isFunctionType()) {
7826 if (!LHSCan->isFunctionType())
7827 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007828 QualType OldReturnType =
7829 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007830 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007831 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007832 QualType ResReturnType =
7833 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7834 if (ResReturnType.isNull())
7835 return QualType();
7836 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7837 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7838 // In either case, use OldReturnType to build the new function type.
7839 const FunctionType *F = LHS->getAs<FunctionType>();
7840 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007841 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7842 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007843 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007844 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007845 return ResultType;
7846 }
7847 }
7848 return QualType();
7849 }
7850
7851 // If the qualifiers are different, the types can still be merged.
7852 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7853 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7854 if (LQuals != RQuals) {
7855 // If any of these qualifiers are different, we have a type mismatch.
7856 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7857 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7858 return QualType();
7859
7860 // Exactly one GC qualifier difference is allowed: __strong is
7861 // okay if the other type has no GC qualifier but is an Objective
7862 // C object pointer (i.e. implicitly strong by default). We fix
7863 // this by pretending that the unqualified type was actually
7864 // qualified __strong.
7865 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7866 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7867 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7868
7869 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7870 return QualType();
7871
7872 if (GC_L == Qualifiers::Strong)
7873 return LHS;
7874 if (GC_R == Qualifiers::Strong)
7875 return RHS;
7876 return QualType();
7877 }
7878
7879 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7880 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7881 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7882 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7883 if (ResQT == LHSBaseQT)
7884 return LHS;
7885 if (ResQT == RHSBaseQT)
7886 return RHS;
7887 }
7888 return QualType();
7889}
7890
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007891//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007892// Integer Predicates
7893//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007894
Jay Foad39c79802011-01-12 09:06:06 +00007895unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007896 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007897 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007898 if (T->isBooleanType())
7899 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007900 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007901 return (unsigned)getTypeSize(T);
7902}
7903
Abramo Bagnara13640492012-09-09 10:21:24 +00007904QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007905 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007906
7907 // Turn <4 x signed int> -> <4 x unsigned int>
7908 if (const VectorType *VTy = T->getAs<VectorType>())
7909 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007910 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007911
7912 // For enums, we return the unsigned version of the base type.
7913 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007914 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007915
7916 const BuiltinType *BTy = T->getAs<BuiltinType>();
7917 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007918 switch (BTy->getKind()) {
7919 case BuiltinType::Char_S:
7920 case BuiltinType::SChar:
7921 return UnsignedCharTy;
7922 case BuiltinType::Short:
7923 return UnsignedShortTy;
7924 case BuiltinType::Int:
7925 return UnsignedIntTy;
7926 case BuiltinType::Long:
7927 return UnsignedLongTy;
7928 case BuiltinType::LongLong:
7929 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007930 case BuiltinType::Int128:
7931 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007932 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007933 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007934 }
7935}
7936
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00007937ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007938
Richard Smith1fa5d642013-05-11 05:45:24 +00007939void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7940 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007941
7942//===----------------------------------------------------------------------===//
7943// Builtin Type Computation
7944//===----------------------------------------------------------------------===//
7945
7946/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007947/// pointer over the consumed characters. This returns the resultant type. If
7948/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7949/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7950/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007951///
7952/// RequiresICE is filled in on return to indicate whether the value is required
7953/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007954static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007955 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007956 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007957 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007958 // Modifiers.
7959 int HowLong = 0;
7960 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007961 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007962
Chris Lattnerdc226c22010-10-01 22:42:38 +00007963 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007964 bool Done = false;
7965 while (!Done) {
7966 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007967 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007968 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007969 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007970 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007971 case 'S':
7972 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7973 assert(!Signed && "Can't use 'S' modifier multiple times!");
7974 Signed = true;
7975 break;
7976 case 'U':
7977 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00007978 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007979 Unsigned = true;
7980 break;
7981 case 'L':
7982 assert(HowLong <= 2 && "Can't have LLLL modifier");
7983 ++HowLong;
7984 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007985 case 'W':
7986 // This modifier represents int64 type.
7987 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7988 switch (Context.getTargetInfo().getInt64Type()) {
7989 default:
7990 llvm_unreachable("Unexpected integer type");
7991 case TargetInfo::SignedLong:
7992 HowLong = 1;
7993 break;
7994 case TargetInfo::SignedLongLong:
7995 HowLong = 2;
7996 break;
7997 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007998 }
7999 }
8000
8001 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008002
Chris Lattnerecd79c62009-06-14 00:45:47 +00008003 // Read the base type.
8004 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008005 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008006 case 'v':
8007 assert(HowLong == 0 && !Signed && !Unsigned &&
8008 "Bad modifiers used with 'v'!");
8009 Type = Context.VoidTy;
8010 break;
Jack Carter24bef982013-08-15 15:16:57 +00008011 case 'h':
8012 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008013 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008014 Type = Context.HalfTy;
8015 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008016 case 'f':
8017 assert(HowLong == 0 && !Signed && !Unsigned &&
8018 "Bad modifiers used with 'f'!");
8019 Type = Context.FloatTy;
8020 break;
8021 case 'd':
8022 assert(HowLong < 2 && !Signed && !Unsigned &&
8023 "Bad modifiers used with 'd'!");
8024 if (HowLong)
8025 Type = Context.LongDoubleTy;
8026 else
8027 Type = Context.DoubleTy;
8028 break;
8029 case 's':
8030 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8031 if (Unsigned)
8032 Type = Context.UnsignedShortTy;
8033 else
8034 Type = Context.ShortTy;
8035 break;
8036 case 'i':
8037 if (HowLong == 3)
8038 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8039 else if (HowLong == 2)
8040 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8041 else if (HowLong == 1)
8042 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8043 else
8044 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8045 break;
8046 case 'c':
8047 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8048 if (Signed)
8049 Type = Context.SignedCharTy;
8050 else if (Unsigned)
8051 Type = Context.UnsignedCharTy;
8052 else
8053 Type = Context.CharTy;
8054 break;
8055 case 'b': // boolean
8056 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8057 Type = Context.BoolTy;
8058 break;
8059 case 'z': // size_t.
8060 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8061 Type = Context.getSizeType();
8062 break;
8063 case 'F':
8064 Type = Context.getCFConstantStringType();
8065 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008066 case 'G':
8067 Type = Context.getObjCIdType();
8068 break;
8069 case 'H':
8070 Type = Context.getObjCSelType();
8071 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008072 case 'M':
8073 Type = Context.getObjCSuperType();
8074 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008075 case 'a':
8076 Type = Context.getBuiltinVaListType();
8077 assert(!Type.isNull() && "builtin va list type not initialized!");
8078 break;
8079 case 'A':
8080 // This is a "reference" to a va_list; however, what exactly
8081 // this means depends on how va_list is defined. There are two
8082 // different kinds of va_list: ones passed by value, and ones
8083 // passed by reference. An example of a by-value va_list is
8084 // x86, where va_list is a char*. An example of by-ref va_list
8085 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8086 // we want this argument to be a char*&; for x86-64, we want
8087 // it to be a __va_list_tag*.
8088 Type = Context.getBuiltinVaListType();
8089 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008090 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008091 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008092 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008093 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008094 break;
8095 case 'V': {
8096 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008097 unsigned NumElements = strtoul(Str, &End, 10);
8098 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008099 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008100
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008101 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8102 RequiresICE, false);
8103 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008104
8105 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008106 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008107 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008108 break;
8109 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008110 case 'E': {
8111 char *End;
8112
8113 unsigned NumElements = strtoul(Str, &End, 10);
8114 assert(End != Str && "Missing vector size");
8115
8116 Str = End;
8117
8118 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8119 false);
8120 Type = Context.getExtVectorType(ElementType, NumElements);
8121 break;
8122 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008123 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008124 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8125 false);
8126 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008127 Type = Context.getComplexType(ElementType);
8128 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008129 }
8130 case 'Y' : {
8131 Type = Context.getPointerDiffType();
8132 break;
8133 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008134 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008135 Type = Context.getFILEType();
8136 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008137 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008138 return QualType();
8139 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008140 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008141 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008142 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008143 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008144 else
8145 Type = Context.getjmp_bufType();
8146
Mike Stump2adb4da2009-07-28 23:47:15 +00008147 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008148 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008149 return QualType();
8150 }
8151 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008152 case 'K':
8153 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8154 Type = Context.getucontext_tType();
8155
8156 if (Type.isNull()) {
8157 Error = ASTContext::GE_Missing_ucontext;
8158 return QualType();
8159 }
8160 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008161 case 'p':
8162 Type = Context.getProcessIDType();
8163 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008164 }
Mike Stump11289f42009-09-09 15:08:12 +00008165
Chris Lattnerdc226c22010-10-01 22:42:38 +00008166 // If there are modifiers and if we're allowed to parse them, go for it.
8167 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008168 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008169 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008170 default: Done = true; --Str; break;
8171 case '*':
8172 case '&': {
8173 // Both pointers and references can have their pointee types
8174 // qualified with an address space.
8175 char *End;
8176 unsigned AddrSpace = strtoul(Str, &End, 10);
8177 if (End != Str && AddrSpace != 0) {
8178 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8179 Str = End;
8180 }
8181 if (c == '*')
8182 Type = Context.getPointerType(Type);
8183 else
8184 Type = Context.getLValueReferenceType(Type);
8185 break;
8186 }
8187 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8188 case 'C':
8189 Type = Type.withConst();
8190 break;
8191 case 'D':
8192 Type = Context.getVolatileType(Type);
8193 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008194 case 'R':
8195 Type = Type.withRestrict();
8196 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008197 }
8198 }
Chris Lattner84733392010-10-01 07:13:18 +00008199
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008200 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008201 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008202
Chris Lattnerecd79c62009-06-14 00:45:47 +00008203 return Type;
8204}
8205
8206/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008207QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008208 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008209 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008210 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008211
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008212 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008213
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008214 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008215 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008216 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8217 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008218 if (Error != GE_None)
8219 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008220
8221 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8222
Chris Lattnerecd79c62009-06-14 00:45:47 +00008223 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008224 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008225 if (Error != GE_None)
8226 return QualType();
8227
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008228 // If this argument is required to be an IntegerConstantExpression and the
8229 // caller cares, fill in the bitmask we return.
8230 if (RequiresICE && IntegerConstantArgs)
8231 *IntegerConstantArgs |= 1 << ArgTypes.size();
8232
Chris Lattnerecd79c62009-06-14 00:45:47 +00008233 // Do array -> pointer decay. The builtin should use the decayed type.
8234 if (Ty->isArrayType())
8235 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008236
Chris Lattnerecd79c62009-06-14 00:45:47 +00008237 ArgTypes.push_back(Ty);
8238 }
8239
David Majnemerba3e5ec2015-03-13 18:26:17 +00008240 if (Id == Builtin::BI__GetExceptionInfo)
8241 return QualType();
8242
Chris Lattnerecd79c62009-06-14 00:45:47 +00008243 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8244 "'.' should only occur at end of builtin type list!");
8245
Reid Kleckner78af0702013-08-27 23:08:25 +00008246 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008247 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8248
8249 bool Variadic = (TypeStr[0] == '.');
8250
8251 // We really shouldn't be making a no-proto type here, especially in C++.
8252 if (ArgTypes.empty() && Variadic)
8253 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008254
John McCalldb40c7f2010-12-14 08:05:40 +00008255 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008256 EPI.ExtInfo = EI;
8257 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008258
Jordan Rose5c382722013-03-08 21:51:21 +00008259 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008260}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008261
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008262static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8263 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008264 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008265 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008266
Rafael Espindola3ae00052013-05-13 00:12:11 +00008267 GVALinkage External = GVA_StrongExternal;
8268 switch (FD->getTemplateSpecializationKind()) {
8269 case TSK_Undeclared:
8270 case TSK_ExplicitSpecialization:
8271 External = GVA_StrongExternal;
8272 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008273
Rafael Espindola3ae00052013-05-13 00:12:11 +00008274 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008275 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008276
David Majnemerc3d07332014-05-15 06:25:57 +00008277 // C++11 [temp.explicit]p10:
8278 // [ Note: The intent is that an inline function that is the subject of
8279 // an explicit instantiation declaration will still be implicitly
8280 // instantiated when used so that the body can be considered for
8281 // inlining, but that no out-of-line copy of the inline function would be
8282 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008283 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008284 return GVA_AvailableExternally;
8285
Rafael Espindola3ae00052013-05-13 00:12:11 +00008286 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008287 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008288 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008289 }
8290
8291 if (!FD->isInlined())
8292 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008293
David Majnemer3f021502015-10-08 04:53:31 +00008294 if ((!Context.getLangOpts().CPlusPlus &&
8295 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008296 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008297 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008298 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8299
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008300 // GNU or C99 inline semantics. Determine whether this symbol should be
8301 // externally visible.
8302 if (FD->isInlineDefinitionExternallyVisible())
8303 return External;
8304
8305 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008306 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008307 }
8308
David Majnemer54e3ba52014-04-02 23:17:29 +00008309 // Functions specified with extern and inline in -fms-compatibility mode
8310 // forcibly get emitted. While the body of the function cannot be later
8311 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008312 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008313 return GVA_StrongODR;
8314
David Majnemer27d69db2014-04-28 22:17:59 +00008315 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008316}
8317
Artem Belevich7b41f702015-09-23 17:44:53 +00008318static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008319 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8320 // dllexport/dllimport on inline functions.
8321 if (D->hasAttr<DLLImportAttr>()) {
8322 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8323 return GVA_AvailableExternally;
Artem Belevich7b41f702015-09-23 17:44:53 +00008324 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008325 if (L == GVA_DiscardableODR)
8326 return GVA_StrongODR;
8327 }
8328 return L;
8329}
8330
8331GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevich7b41f702015-09-23 17:44:53 +00008332 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8333 FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008334}
8335
8336static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8337 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008338 if (!VD->isExternallyVisible())
8339 return GVA_Internal;
8340
David Majnemer27d69db2014-04-28 22:17:59 +00008341 if (VD->isStaticLocal()) {
8342 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8343 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8344 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8345 LexicalContext = LexicalContext->getLexicalParent();
8346
Richard Smith9e2341d2015-03-23 03:25:59 +00008347 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008348 // enclosing function.
8349 if (LexicalContext)
8350 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008351 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008352
8353 // GVA_StrongODR function linkage is stronger than what we need,
8354 // downgrade to GVA_DiscardableODR.
8355 // This allows us to discard the variable if we never end up needing it.
8356 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8357 : StaticLocalLinkage;
8358 }
8359
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008360 // MSVC treats in-class initialized static data members as definitions.
8361 // By giving them non-strong linkage, out-of-line definitions won't
8362 // cause link errors.
8363 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8364 return GVA_DiscardableODR;
8365
Richard Smith8809a0c2013-09-27 20:14:12 +00008366 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008367 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008368 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008369
David Majnemer6d1780c2015-07-17 23:36:49 +00008370 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008371 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8372 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008373 ? GVA_StrongODR
8374 : GVA_StrongExternal;
8375
Rafael Espindola3ae00052013-05-13 00:12:11 +00008376 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008377 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008378
David Majnemer27d69db2014-04-28 22:17:59 +00008379 case TSK_ExplicitInstantiationDeclaration:
8380 return GVA_AvailableExternally;
8381
Rafael Espindola3ae00052013-05-13 00:12:11 +00008382 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008383 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008384 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008385
8386 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008387}
8388
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008389GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevich7b41f702015-09-23 17:44:53 +00008390 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8391 VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008392}
8393
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008394bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008395 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8396 if (!VD->isFileVarDecl())
8397 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008398 // Global named register variables (GNU extension) are never emitted.
8399 if (VD->getStorageClass() == SC_Register)
8400 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008401 if (VD->getDescribedVarTemplate() ||
8402 isa<VarTemplatePartialSpecializationDecl>(VD))
8403 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008404 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8405 // We never need to emit an uninstantiated function template.
8406 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8407 return false;
Alexey Bataev97720002014-11-11 04:05:39 +00008408 } else if (isa<OMPThreadPrivateDecl>(D))
8409 return true;
8410 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008411 return false;
8412
8413 // If this is a member of a class template, we do not need to emit it.
8414 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008415 return false;
8416
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008417 // Weak references don't produce any output by themselves.
8418 if (D->hasAttr<WeakRefAttr>())
8419 return false;
8420
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008421 // Aliases and used decls are required.
8422 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8423 return true;
8424
8425 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8426 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008427 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008428 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008429
8430 // Constructors and destructors are required.
8431 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8432 return true;
8433
John McCall6bd2a892013-01-25 22:31:03 +00008434 // The key function for a class is required. This rule only comes
8435 // into play when inline functions can be key functions, though.
8436 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8437 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8438 const CXXRecordDecl *RD = MD->getParent();
8439 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8440 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8441 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8442 return true;
8443 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008444 }
8445 }
8446
8447 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8448
8449 // static, static inline, always_inline, and extern inline functions can
8450 // always be deferred. Normal inline functions can be deferred in C99/C++.
8451 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008452 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8453 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008454 return false;
8455 return true;
8456 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008457
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008458 const VarDecl *VD = cast<VarDecl>(D);
8459 assert(VD->isFileVarDecl() && "Expected file scoped var");
8460
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008461 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8462 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008463 return false;
8464
Richard Smitha0e5e542012-11-12 21:38:00 +00008465 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008466 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008467 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8468 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008469 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008470
Richard Smitha0e5e542012-11-12 21:38:00 +00008471 // Variables that have destruction with side-effects are required.
8472 if (VD->getType().isDestructedType())
8473 return true;
8474
8475 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008476 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8477 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008478 return true;
8479
8480 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008481}
Charles Davis53c59df2010-08-16 03:33:14 +00008482
Reid Kleckner78af0702013-08-27 23:08:25 +00008483CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8484 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008485 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008486 if (IsCXXMethod)
8487 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008488
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008489 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8490
8491 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008492}
8493
Jay Foad39c79802011-01-12 09:06:06 +00008494bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008495 // Pass through to the C++ ABI object
8496 return ABI->isNearlyEmpty(RD);
8497}
8498
Reid Kleckner96f8f932014-02-05 17:27:08 +00008499VTableContextBase *ASTContext::getVTableContext() {
8500 if (!VTContext.get()) {
8501 if (Target->getCXXABI().isMicrosoft())
8502 VTContext.reset(new MicrosoftVTableContext(*this));
8503 else
8504 VTContext.reset(new ItaniumVTableContext(*this));
8505 }
8506 return VTContext.get();
8507}
8508
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008509MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008510 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008511 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008512 case TargetCXXABI::GenericItanium:
8513 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008514 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008515 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008516 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008517 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008518 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008519 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008520 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008521 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008522 }
David Blaikie83d382b2011-09-23 05:06:16 +00008523 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008524}
8525
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008526CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008527
8528size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008529 return ASTRecordLayouts.getMemorySize() +
8530 llvm::capacity_in_bytes(ObjCLayouts) +
8531 llvm::capacity_in_bytes(KeyFunctions) +
8532 llvm::capacity_in_bytes(ObjCImpls) +
8533 llvm::capacity_in_bytes(BlockVarCopyInits) +
8534 llvm::capacity_in_bytes(DeclAttrs) +
8535 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8536 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8537 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8538 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8539 llvm::capacity_in_bytes(OverriddenMethods) +
8540 llvm::capacity_in_bytes(Types) +
8541 llvm::capacity_in_bytes(VariableArrayTypes) +
8542 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008543}
Ted Kremenek540017e2011-10-06 05:00:56 +00008544
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008545/// getIntTypeForBitwidth -
8546/// sets integer QualTy according to specified details:
8547/// bitwidth, signed/unsigned.
8548/// Returns empty type if there is no appropriate target types.
8549QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8550 unsigned Signed) const {
8551 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8552 CanQualType QualTy = getFromTargetType(Ty);
8553 if (!QualTy && DestWidth == 128)
8554 return Signed ? Int128Ty : UnsignedInt128Ty;
8555 return QualTy;
8556}
8557
8558/// getRealTypeForBitwidth -
8559/// sets floating point QualTy according to specified bitwidth.
8560/// Returns empty type if there is no appropriate target types.
8561QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8562 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8563 switch (Ty) {
8564 case TargetInfo::Float:
8565 return FloatTy;
8566 case TargetInfo::Double:
8567 return DoubleTy;
8568 case TargetInfo::LongDouble:
8569 return LongDoubleTy;
8570 case TargetInfo::NoFloat:
8571 return QualType();
8572 }
8573
8574 llvm_unreachable("Unhandled TargetInfo::RealType value");
8575}
8576
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008577void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8578 if (Number > 1)
8579 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008580}
8581
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008582unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8583 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8584 MangleNumbers.find(ND);
8585 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008586}
8587
David Majnemer2206bf52014-03-05 08:57:59 +00008588void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8589 if (Number > 1)
8590 StaticLocalNumbers[VD] = Number;
8591}
8592
8593unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8594 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8595 StaticLocalNumbers.find(VD);
8596 return I != StaticLocalNumbers.end() ? I->second : 1;
8597}
8598
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008599MangleNumberingContext &
8600ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008601 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8602 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8603 if (!MCtx)
8604 MCtx = createMangleNumberingContext();
8605 return *MCtx;
8606}
8607
8608MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8609 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008610}
8611
David Majnemere7a818f2015-03-06 18:53:55 +00008612const CXXConstructorDecl *
8613ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8614 return ABI->getCopyConstructorForExceptionObject(
8615 cast<CXXRecordDecl>(RD->getFirstDecl()));
8616}
8617
8618void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8619 CXXConstructorDecl *CD) {
8620 return ABI->addCopyConstructorForExceptionObject(
8621 cast<CXXRecordDecl>(RD->getFirstDecl()),
8622 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8623}
8624
David Majnemerdfa6d202015-03-11 18:36:39 +00008625void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8626 unsigned ParmIdx, Expr *DAE) {
8627 ABI->addDefaultArgExprForConstructor(
8628 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8629}
8630
8631Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8632 unsigned ParmIdx) {
8633 return ABI->getDefaultArgExprForConstructor(
8634 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8635}
8636
David Majnemer00350522015-08-31 18:48:39 +00008637void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8638 TypedefNameDecl *DD) {
8639 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8640}
8641
8642TypedefNameDecl *
8643ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8644 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8645}
8646
8647void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8648 DeclaratorDecl *DD) {
8649 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8650}
8651
8652DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8653 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8654}
8655
Ted Kremenek540017e2011-10-06 05:00:56 +00008656void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8657 ParamIndices[D] = index;
8658}
8659
8660unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8661 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8662 assert(I != ParamIndices.end() &&
8663 "ParmIndices lacks entry set by ParmVarDecl");
8664 return I->second;
8665}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008666
Richard Smithe6c01442013-06-05 00:46:14 +00008667APValue *
8668ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8669 bool MayCreate) {
8670 assert(E && E->getStorageDuration() == SD_Static &&
8671 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008672 if (MayCreate) {
8673 APValue *&MTVI = MaterializedTemporaryValues[E];
8674 if (!MTVI)
8675 MTVI = new (*this) APValue;
8676 return MTVI;
8677 }
Richard Smithe6c01442013-06-05 00:46:14 +00008678
David Majnemer2dcef9e2015-08-13 23:50:15 +00008679 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008680}
8681
Fariborz Jahanian615de762013-05-28 17:37:39 +00008682bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8683 const llvm::Triple &T = getTargetInfo().getTriple();
8684 if (!T.isOSDarwin())
8685 return false;
8686
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008687 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8688 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8689 return false;
8690
Fariborz Jahanian615de762013-05-28 17:37:39 +00008691 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8692 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8693 uint64_t Size = sizeChars.getQuantity();
8694 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8695 unsigned Align = alignChars.getQuantity();
8696 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8697 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8698}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008699
8700namespace {
8701
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008702ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8703 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008704 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008705 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008706 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008707 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008708 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008709}
8710
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008711/// Template specializations to abstract away from pointers and TypeLocs.
8712/// @{
8713template <typename T>
8714ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8715 return ast_type_traits::DynTypedNode::create(*Node);
8716}
8717template <>
8718ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8719 return ast_type_traits::DynTypedNode::create(Node);
8720}
8721template <>
8722ast_type_traits::DynTypedNode
8723createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8724 return ast_type_traits::DynTypedNode::create(Node);
8725}
8726/// @}
8727
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008728 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8729 /// parents as defined by the \c RecursiveASTVisitor.
8730 ///
8731 /// Note that the relationship described here is purely in terms of AST
8732 /// traversal - there are other relationships (for example declaration context)
8733 /// in the AST that are better modeled by special matchers.
8734 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008735 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008736 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8737
8738 public:
8739 /// \brief Builds and returns the translation unit's parent map.
8740 ///
8741 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008742 static std::pair<ASTContext::ParentMapPointers *,
8743 ASTContext::ParentMapOtherNodes *>
8744 buildMap(TranslationUnitDecl &TU) {
8745 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8746 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008747 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008748 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008749 }
8750
8751 private:
8752 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8753
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008754 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8755 ASTContext::ParentMapOtherNodes *OtherParents)
8756 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008757
8758 bool shouldVisitTemplateInstantiations() const {
8759 return true;
8760 }
8761 bool shouldVisitImplicitCode() const {
8762 return true;
8763 }
8764 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8765 // are not triggered during data recursion.
8766 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8767 return false;
8768 }
8769
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008770 template <typename T, typename MapNodeTy, typename MapTy>
8771 bool TraverseNode(T Node, MapNodeTy MapNode,
8772 bool (VisitorBase::*traverse)(T), MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00008773 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008774 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008775 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008776 // FIXME: Currently we add the same parent multiple times, but only
8777 // when no memoization data is available for the type.
8778 // For example when we visit all subexpressions of template
8779 // instantiations; this is suboptimal, but benign: the only way to
8780 // visit those is with hasAncestor / hasParent, and those do not create
8781 // new matches.
8782 // The plan is to enable DynTypedNode to be storable in a map or hash
8783 // map. The main problem there is to implement hash functions /
8784 // comparison operators for all types that DynTypedNode supports that
8785 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008786 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00008787 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008788 if (const auto *D = ParentStack.back().get<Decl>())
8789 NodeOrVector = D;
8790 else if (const auto *S = ParentStack.back().get<Stmt>())
8791 NodeOrVector = S;
8792 else
8793 NodeOrVector =
8794 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008795 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008796 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8797 auto *Vector = new ASTContext::ParentVector(
8798 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008799 if (auto *Node =
8800 NodeOrVector
8801 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8802 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00008803 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008804 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008805
8806 auto *Vector =
8807 NodeOrVector.template get<ASTContext::ParentVector *>();
8808 // Skip duplicates for types that have memoization data.
8809 // We must check that the type has memoization data before calling
8810 // std::find() because DynTypedNode::operator== can't compare all
8811 // types.
8812 bool Found = ParentStack.back().getMemoizationData() &&
8813 std::find(Vector->begin(), Vector->end(),
8814 ParentStack.back()) != Vector->end();
8815 if (!Found)
8816 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008817 }
8818 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008819 ParentStack.push_back(createDynTypedNode(Node));
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008820 bool Result = (this ->* traverse) (Node);
8821 ParentStack.pop_back();
8822 return Result;
8823 }
8824
8825 bool TraverseDecl(Decl *DeclNode) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008826 return TraverseNode(DeclNode, DeclNode, &VisitorBase::TraverseDecl,
8827 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008828 }
8829
8830 bool TraverseStmt(Stmt *StmtNode) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008831 return TraverseNode(StmtNode, StmtNode, &VisitorBase::TraverseStmt,
8832 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008833 }
8834
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008835 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
8836 return TraverseNode(TypeLocNode,
8837 ast_type_traits::DynTypedNode::create(TypeLocNode),
8838 &VisitorBase::TraverseTypeLoc, OtherParents);
8839 }
8840
8841 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
8842 return TraverseNode(
8843 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
8844 &VisitorBase::TraverseNestedNameSpecifierLoc, OtherParents);
8845 }
8846
8847 ASTContext::ParentMapPointers *Parents;
8848 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008849 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8850
8851 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8852 };
8853
8854} // end namespace
8855
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008856template <typename NodeTy, typename MapTy>
8857static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
8858 const MapTy &Map) {
8859 auto I = Map.find(Node);
8860 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008861 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008862 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008863 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008864 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00008865 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008866 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008867}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008868
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008869ASTContext::DynTypedNodeList
8870ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8871 if (!PointerParents) {
8872 // We always need to run over the whole translation unit, as
8873 // hasAncestor can escape any subtree.
8874 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
8875 PointerParents.reset(Maps.first);
8876 OtherParents.reset(Maps.second);
8877 }
8878 if (Node.getNodeKind().hasPointerIdentity())
8879 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
8880 return getDynNodeFromMap(Node, *OtherParents);
8881}
8882
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008883bool
8884ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8885 const ObjCMethodDecl *MethodImpl) {
8886 // No point trying to match an unavailable/deprecated mothod.
8887 if (MethodDecl->hasAttr<UnavailableAttr>()
8888 || MethodDecl->hasAttr<DeprecatedAttr>())
8889 return false;
8890 if (MethodDecl->getObjCDeclQualifier() !=
8891 MethodImpl->getObjCDeclQualifier())
8892 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008893 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008894 return false;
8895
8896 if (MethodDecl->param_size() != MethodImpl->param_size())
8897 return false;
8898
8899 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8900 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8901 EF = MethodDecl->param_end();
8902 IM != EM && IF != EF; ++IM, ++IF) {
8903 const ParmVarDecl *DeclVar = (*IF);
8904 const ParmVarDecl *ImplVar = (*IM);
8905 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8906 return false;
8907 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8908 return false;
8909 }
8910 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8911
8912}
Richard Smith053f6c62014-05-16 23:01:30 +00008913
8914// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8915// doesn't include ASTContext.h
8916template
8917clang::LazyGenerationalUpdatePtr<
8918 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8919clang::LazyGenerationalUpdatePtr<
8920 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8921 const clang::ASTContext &Ctx, Decl *Value);