blob: aa9277cdc1aa9c6d23c92ea6ec640e249291bb89 [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"
Chandler Carruthaa36b892015-12-30 03:40:23 +000022#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000029#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000031#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000033#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000034#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000035#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000036#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000037#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000038#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000039#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000040#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000041#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000042#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000043#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000044
Chris Lattnerddc135e2006-11-10 06:34:16 +000045using namespace clang;
46
Douglas Gregor9672f922010-07-03 00:47:00 +000047unsigned ASTContext::NumImplicitDefaultConstructors;
48unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000049unsigned ASTContext::NumImplicitCopyConstructors;
50unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000051unsigned ASTContext::NumImplicitMoveConstructors;
52unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000053unsigned ASTContext::NumImplicitCopyAssignmentOperators;
54unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000055unsigned ASTContext::NumImplicitMoveAssignmentOperators;
56unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000057unsigned ASTContext::NumImplicitDestructors;
58unsigned ASTContext::NumImplicitDestructorsDeclared;
59
Steve Naroff0af91202007-04-27 21:51:21 +000060enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000061 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000062};
63
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000064RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000065 if (!CommentsLoaded && ExternalSource) {
66 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000067
68#ifndef NDEBUG
69 ArrayRef<RawComment *> RawComments = Comments.getComments();
70 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
71 BeforeThanCompare<RawComment>(SourceMgr)));
72#endif
73
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000074 CommentsLoaded = true;
75 }
76
77 assert(D);
78
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000079 // User can not attach documentation to implicit declarations.
80 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000081 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000082
Dmitri Gribenkob2610882012-08-14 17:17:18 +000083 // User can not attach documentation to implicit instantiations.
84 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
85 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000086 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000087 }
88
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000089 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
90 if (VD->isStaticDataMember() &&
91 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000092 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000093 }
94
95 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
96 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000097 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000098 }
99
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000100 if (const ClassTemplateSpecializationDecl *CTSD =
101 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
102 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
103 if (TSK == TSK_ImplicitInstantiation ||
104 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000105 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000106 }
107
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000108 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
109 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000110 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000111 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000112 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
113 // When tag declaration (but not definition!) is part of the
114 // decl-specifier-seq of some other declaration, it doesn't get comment
115 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000116 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000117 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000118 // TODO: handle comments for function parameters properly.
119 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000120 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000121
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000122 // TODO: we could look up template parameter documentation in the template
123 // documentation.
124 if (isa<TemplateTypeParmDecl>(D) ||
125 isa<NonTypeTemplateParmDecl>(D) ||
126 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000127 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000128
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000129 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000130
131 // If there are no comments anywhere, we won't find anything.
132 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000133 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000134
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000135 // Find declaration location.
136 // For Objective-C declarations we generally don't expect to have multiple
137 // declarators, thus use declaration starting location as the "declaration
138 // location".
139 // For all other declarations multiple declarators are used quite frequently,
140 // so we use the location of the identifier as the "declaration location".
141 SourceLocation DeclLoc;
142 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000143 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000144 isa<RedeclarableTemplateDecl>(D) ||
145 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000146 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000147 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000148 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000149 if (DeclLoc.isMacroID()) {
150 if (isa<TypedefDecl>(D)) {
151 // If location of the typedef name is in a macro, it is because being
152 // declared via a macro. Try using declaration's starting location as
153 // the "declaration location".
154 DeclLoc = D->getLocStart();
155 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
156 // If location of the tag decl is inside a macro, but the spelling of
157 // the tag name comes from a macro argument, it looks like a special
158 // macro like NS_ENUM is being used to define the tag decl. In that
159 // case, adjust the source location to the expansion loc so that we can
160 // attach the comment to the tag decl.
161 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
162 TD->isCompleteDefinition())
163 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
164 }
165 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000166 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000167
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000168 // If the declaration doesn't map directly to a location in a file, we
169 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000171 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000172
173 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000174 ArrayRef<RawComment *>::iterator Comment;
175 {
176 // When searching for comments during parsing, the comment we are looking
177 // for is usually among the last two comments we parsed -- check them
178 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000179 RawComment CommentAtDeclLoc(
180 SourceMgr, SourceRange(DeclLoc), false,
181 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000182 BeforeThanCompare<RawComment> Compare(SourceMgr);
183 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
184 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
185 if (!Found && RawComments.size() >= 2) {
186 MaybeBeforeDecl--;
187 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
188 }
189
190 if (Found) {
191 Comment = MaybeBeforeDecl + 1;
192 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
193 &CommentAtDeclLoc, Compare));
194 } else {
195 // Slow path.
196 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
197 &CommentAtDeclLoc, Compare);
198 }
199 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000200
201 // Decompose the location for the declaration and find the beginning of the
202 // file buffer.
203 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
204
205 // First check whether we have a trailing comment.
206 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000207 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000208 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000209 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000210 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000211 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000212 // Check that Doxygen trailing comment comes after the declaration, starts
213 // on the same line and in the same file as the declaration.
214 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
215 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
216 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
217 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000218 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000219 }
220 }
221
222 // The comment just after the declaration was not a trailing comment.
223 // Let's look at the previous comment.
224 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000225 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000226 --Comment;
227
228 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000229 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000230 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000231
232 // Decompose the end of the comment.
233 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000234 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000235
236 // If the comment and the declaration aren't in the same file, then they
237 // aren't related.
238 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000239 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000240
241 // Get the corresponding buffer.
242 bool Invalid = false;
243 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
244 &Invalid).data();
245 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000246 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000247
248 // Extract text between the comment and declaration.
249 StringRef Text(Buffer + CommentEndDecomp.second,
250 DeclLocDecomp.second - CommentEndDecomp.second);
251
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000252 // There should be no other declarations or preprocessor directives between
253 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000254 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000255 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000256
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000257 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000258}
259
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000260namespace {
261/// If we have a 'templated' declaration for a template, adjust 'D' to
262/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000263/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000264const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000265 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000266 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000267 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000268 return FTD;
269
270 // Nothing to do if function is not an implicit instantiation.
271 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
272 return D;
273
274 // Function is an implicit instantiation of a function template?
275 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
276 return FTD;
277
278 // Function is instantiated from a member definition of a class template?
279 if (const FunctionDecl *MemberDecl =
280 FD->getInstantiatedFromMemberFunction())
281 return MemberDecl;
282
283 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000284 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000285 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
286 // Static data member is instantiated from a member definition of a class
287 // template?
288 if (VD->isStaticDataMember())
289 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
290 return MemberDecl;
291
292 return D;
293 }
294 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
295 // Is this class declaration part of a class template?
296 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
297 return CTD;
298
299 // Class is an implicit instantiation of a class template or partial
300 // specialization?
301 if (const ClassTemplateSpecializationDecl *CTSD =
302 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
303 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
304 return D;
305 llvm::PointerUnion<ClassTemplateDecl *,
306 ClassTemplatePartialSpecializationDecl *>
307 PU = CTSD->getSpecializedTemplateOrPartial();
308 return PU.is<ClassTemplateDecl*>() ?
309 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
310 static_cast<const Decl*>(
311 PU.get<ClassTemplatePartialSpecializationDecl *>());
312 }
313
314 // Class is instantiated from a member definition of a class template?
315 if (const MemberSpecializationInfo *Info =
316 CRD->getMemberSpecializationInfo())
317 return Info->getInstantiatedFrom();
318
319 return D;
320 }
321 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
322 // Enum is instantiated from a member definition of a class template?
323 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
324 return MemberDecl;
325
326 return D;
327 }
328 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000329 return D;
330}
Eugene Zelenkod4304d22015-11-04 21:37:17 +0000331} // anonymous namespace
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000332
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000333const RawComment *ASTContext::getRawCommentForAnyRedecl(
334 const Decl *D,
335 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000336 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000337
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000338 // Check whether we have cached a comment for this declaration already.
339 {
340 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
341 RedeclComments.find(D);
342 if (Pos != RedeclComments.end()) {
343 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000344 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
345 if (OriginalDecl)
346 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000347 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000348 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000349 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000350 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000351
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000352 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000353 const RawComment *RC = nullptr;
354 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000355 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000356 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000357 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000358 if (Pos != RedeclComments.end()) {
359 const RawCommentAndCacheFlags &Raw = Pos->second;
360 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
361 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000362 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000363 break;
364 }
365 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000366 RC = getRawCommentForDeclNoCache(I);
367 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000368 RawCommentAndCacheFlags Raw;
369 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000370 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
371 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000372 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000373 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000374 } else
375 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000376 Raw.setOriginalDecl(I);
377 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000378 if (RC)
379 break;
380 }
381 }
382
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000383 // If we found a comment, it should be a documentation comment.
384 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000385
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000386 if (OriginalDecl)
387 *OriginalDecl = OriginalDeclForRC;
388
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000389 // Update cache for every declaration in the redeclaration chain.
390 RawCommentAndCacheFlags Raw;
391 Raw.setRaw(RC);
392 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000393 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000394
Aaron Ballman86c93902014-03-06 23:45:36 +0000395 for (auto I : D->redecls()) {
396 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000397 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
398 R = Raw;
399 }
400
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000401 return RC;
402}
403
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000404static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
405 SmallVectorImpl<const NamedDecl *> &Redeclared) {
406 const DeclContext *DC = ObjCMethod->getDeclContext();
407 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
408 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
409 if (!ID)
410 return;
411 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000412 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000413 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000414 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000415 ObjCMethod->isInstanceMethod()))
416 Redeclared.push_back(RedeclaredMethod);
417 }
418 }
419}
420
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000421comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
422 const Decl *D) const {
423 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
424 ThisDeclInfo->CommentDecl = D;
425 ThisDeclInfo->IsFilled = false;
426 ThisDeclInfo->fill();
427 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000428 if (!ThisDeclInfo->TemplateParameters)
429 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000430 comments::FullComment *CFC =
431 new (*this) comments::FullComment(FC->getBlocks(),
432 ThisDeclInfo);
433 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000434}
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(),
David Majnemer902f8c62015-12-27 07:16:27 +0000664 CanonParams,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000665 SourceLocation()));
666
667 // Get the new insert position for the node we care about.
668 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000669 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000670 (void)Canonical;
671
672 // Create the canonical template template parameter entry.
673 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
674 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
675 return CanonTTP;
676}
677
Charles Davis53c59df2010-08-16 03:33:14 +0000678CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000679 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000680
John McCall359b8852013-01-25 22:30:49 +0000681 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000682 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000683 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000684 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000685 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000686 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000687 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000688 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000689 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000690 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000691 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000692 return CreateMicrosoftCXXABI(*this);
693 }
David Blaikie8a40f702012-01-17 06:56:22 +0000694 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000695}
696
Douglas Gregore8bbc122011-09-02 00:18:52 +0000697static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000698 const LangOptions &LOpts) {
699 if (LOpts.FakeAddressSpaceMap) {
700 // The fake address space map must have a distinct entry for each
701 // language-specific address space.
702 static const unsigned FakeAddrSpaceMap[] = {
703 1, // opencl_global
704 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000705 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000706 4, // opencl_generic
707 5, // cuda_device
708 6, // cuda_constant
709 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000710 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000712 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000713 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000714 }
715}
716
David Tweed31d09b02013-09-13 12:04:22 +0000717static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
718 const LangOptions &LangOpts) {
719 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000720 case LangOptions::ASMM_Target:
721 return TI.useAddressSpaceMapMangling();
722 case LangOptions::ASMM_On:
723 return true;
724 case LangOptions::ASMM_Off:
725 return false;
726 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000727 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000728}
729
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000730ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000731 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000732 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000733 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
734 DependentTemplateSpecializationTypes(this_()),
735 SubstTemplateTemplateParmPacks(this_()),
736 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
737 UInt128Decl(nullptr), Float128StubDecl(nullptr),
Charles Davisc7d5c942015-09-17 20:55:33 +0000738 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
739 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
740 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000741 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
742 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
743 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
744 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
745 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
746 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr), SourceMgr(SM),
747 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.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000765 for (auto &Pair : Deallocations)
766 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000767
Ted Kremenek076baeb2010-06-08 23:00:58 +0000768 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000769 // because they can contain DenseMaps.
770 for (llvm::DenseMap<const ObjCContainerDecl*,
771 const ASTRecordLayout*>::iterator
772 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
773 // Increment in loop to prevent using deallocated memory.
774 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
775 R->Destroy(*this);
776
Ted Kremenek076baeb2010-06-08 23:00:58 +0000777 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
778 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
779 // Increment in loop to prevent using deallocated memory.
780 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
781 R->Destroy(*this);
782 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000783
784 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
785 AEnd = DeclAttrs.end();
786 A != AEnd; ++A)
787 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000788
David Majnemere694f3e2015-08-14 14:43:50 +0000789 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
790 MaterializedTemporaryValues)
791 MTVPair.second->~APValue();
792
Reid Kleckner588c9372014-02-19 23:44:52 +0000793 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000794}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000795
Manuel Klimek95403e62014-05-21 13:28:59 +0000796void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000797 if (!PointerParents) return;
798 for (const auto &Entry : *PointerParents) {
799 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
800 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
801 } else if (Entry.second.is<ParentVector *>()) {
802 delete Entry.second.get<ParentVector *>();
803 }
804 }
805 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000806 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
807 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000808 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000809 delete Entry.second.get<ParentVector *>();
810 }
811 }
812}
813
Douglas Gregor1a809332010-05-23 18:26:36 +0000814void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000815 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000816}
817
Mike Stump11289f42009-09-09 15:08:12 +0000818void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000819ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
820 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000821}
822
Chris Lattner4eb445d2007-01-26 01:27:23 +0000823void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000824 llvm::errs() << "\n*** AST Context Stats:\n";
825 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000826
Douglas Gregora30d0462009-05-26 14:40:08 +0000827 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000828#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000829#define ABSTRACT_TYPE(Name, Parent)
830#include "clang/AST/TypeNodes.def"
831 0 // Extra
832 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000833
Chris Lattner4eb445d2007-01-26 01:27:23 +0000834 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
835 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000836 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000837 }
838
Douglas Gregora30d0462009-05-26 14:40:08 +0000839 unsigned Idx = 0;
840 unsigned TotalBytes = 0;
841#define TYPE(Name, Parent) \
842 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000843 llvm::errs() << " " << counts[Idx] << " " << #Name \
844 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000845 TotalBytes += counts[Idx] * sizeof(Name##Type); \
846 ++Idx;
847#define ABSTRACT_TYPE(Name, Parent)
848#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000849
Chandler Carruth3c147a72011-07-04 05:32:14 +0000850 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
851
Douglas Gregor7454c562010-07-02 20:37:36 +0000852 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
854 << NumImplicitDefaultConstructors
855 << " implicit default constructors created\n";
856 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
857 << NumImplicitCopyConstructors
858 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000859 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000860 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
861 << NumImplicitMoveConstructors
862 << " implicit move constructors created\n";
863 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
864 << NumImplicitCopyAssignmentOperators
865 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000866 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000867 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
868 << NumImplicitMoveAssignmentOperators
869 << " implicit move assignment operators created\n";
870 llvm::errs() << NumImplicitDestructorsDeclared << "/"
871 << NumImplicitDestructors
872 << " implicit destructors created\n";
873
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000874 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000875 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000876 ExternalSource->PrintStats();
877 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000878
Douglas Gregor5b11d492010-07-25 17:53:33 +0000879 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000880}
881
Richard Smith42413142015-05-15 20:05:43 +0000882void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
883 bool NotifyListeners) {
884 if (NotifyListeners)
885 if (auto *Listener = getASTMutationListener())
886 Listener->RedefinedHiddenDefinition(ND, M);
887
888 if (getLangOpts().ModulesLocalVisibility)
889 MergedDefModules[ND].push_back(M);
890 else
891 ND->setHidden(false);
892}
893
894void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
895 auto It = MergedDefModules.find(ND);
896 if (It == MergedDefModules.end())
897 return;
898
899 auto &Merged = It->second;
900 llvm::DenseSet<Module*> Found;
901 for (Module *&M : Merged)
902 if (!Found.insert(M).second)
903 M = nullptr;
904 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
905}
906
Richard Smithf19e1272015-03-07 00:04:49 +0000907ExternCContextDecl *ASTContext::getExternCContextDecl() const {
908 if (!ExternCContext)
909 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
910
911 return ExternCContext;
912}
913
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000914BuiltinTemplateDecl *
915ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
916 const IdentifierInfo *II) const {
917 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
918 BuiltinTemplate->setImplicit();
919 TUDecl->addDecl(BuiltinTemplate);
920
921 return BuiltinTemplate;
922}
923
924BuiltinTemplateDecl *
925ASTContext::getMakeIntegerSeqDecl() const {
926 if (!MakeIntegerSeqDecl)
927 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
928 getMakeIntegerSeqName());
929 return MakeIntegerSeqDecl;
930}
931
Alp Toker2dea15b2013-12-17 01:22:38 +0000932RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
933 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000934 SourceLocation Loc;
935 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000936 if (getLangOpts().CPlusPlus)
937 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
938 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000939 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000940 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
941 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000942 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000943 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
944 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000945 return NewDecl;
946}
947
948TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
949 StringRef Name) const {
950 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
951 TypedefDecl *NewDecl = TypedefDecl::Create(
952 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
953 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
954 NewDecl->setImplicit();
955 return NewDecl;
956}
957
Douglas Gregor801c99d2011-08-12 06:49:56 +0000958TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000959 if (!Int128Decl)
960 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000961 return Int128Decl;
962}
963
964TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000965 if (!UInt128Decl)
966 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000967 return UInt128Decl;
968}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000969
Nico Webere1687c52013-06-20 21:44:55 +0000970TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000971 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000972 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000973 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000974
Nico Webere1687c52013-06-20 21:44:55 +0000975 return Float128StubDecl;
976}
977
John McCall48f2d582009-10-23 23:03:21 +0000978void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000979 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000980 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000981 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000982}
983
Artem Belevichb5bc9232015-09-22 17:23:22 +0000984void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
985 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000986 assert((!this->Target || this->Target == &Target) &&
987 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000988 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000989
Douglas Gregore8bbc122011-09-02 00:18:52 +0000990 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000991 this->AuxTarget = AuxTarget;
992
Douglas Gregore8bbc122011-09-02 00:18:52 +0000993 ABI.reset(createCXXABI(Target));
994 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000995 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000996
Chris Lattner970e54e2006-11-12 00:37:36 +0000997 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000998 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000999
Chris Lattner970e54e2006-11-12 00:37:36 +00001000 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001001 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001002 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001003 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001004 InitBuiltinType(CharTy, BuiltinType::Char_S);
1005 else
1006 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001007 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001008 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1009 InitBuiltinType(ShortTy, BuiltinType::Short);
1010 InitBuiltinType(IntTy, BuiltinType::Int);
1011 InitBuiltinType(LongTy, BuiltinType::Long);
1012 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001013
Chris Lattner970e54e2006-11-12 00:37:36 +00001014 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001015 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1016 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1017 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1018 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1019 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001020
Chris Lattner970e54e2006-11-12 00:37:36 +00001021 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001022 InitBuiltinType(FloatTy, BuiltinType::Float);
1023 InitBuiltinType(DoubleTy, BuiltinType::Double);
1024 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001025
Chris Lattnerf122cef2009-04-30 02:43:43 +00001026 // GNU extension, 128-bit integers.
1027 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1028 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1029
Hans Wennborg0d81e012013-05-10 10:08:40 +00001030 // C++ 3.9.1p5
1031 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1032 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1033 else // -fshort-wchar makes wchar_t be unsigned.
1034 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1035 if (LangOpts.CPlusPlus && LangOpts.WChar)
1036 WideCharTy = WCharTy;
1037 else {
1038 // C99 (or C++ using -fno-wchar).
1039 WideCharTy = getFromTargetType(Target.getWCharType());
1040 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001041
James Molloy36365542012-05-04 10:55:22 +00001042 WIntTy = getFromTargetType(Target.getWIntType());
1043
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001044 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1045 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1046 else // C99
1047 Char16Ty = getFromTargetType(Target.getChar16Type());
1048
1049 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1050 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1051 else // C99
1052 Char32Ty = getFromTargetType(Target.getChar32Type());
1053
Douglas Gregor4619e432008-12-05 23:32:09 +00001054 // Placeholder type for type-dependent expressions whose type is
1055 // completely unknown. No code should ever check a type against
1056 // DependentTy and users should never see it; however, it is here to
1057 // help diagnose failures to properly check for type-dependent
1058 // expressions.
1059 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001060
John McCall36e7fe32010-10-12 00:20:44 +00001061 // Placeholder type for functions.
1062 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1063
John McCall0009fcc2011-04-26 20:42:42 +00001064 // Placeholder type for bound members.
1065 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1066
John McCall526ab472011-10-25 17:37:35 +00001067 // Placeholder type for pseudo-objects.
1068 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1069
John McCall31996342011-04-07 08:22:57 +00001070 // "any" type; useful for debugger-like clients.
1071 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1072
John McCall8a6b59a2011-10-17 18:09:15 +00001073 // Placeholder type for unbridged ARC casts.
1074 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1075
Eli Friedman34866c72012-08-31 00:14:07 +00001076 // Placeholder type for builtin functions.
1077 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1078
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001079 // Placeholder type for OMP array sections.
1080 if (LangOpts.OpenMP)
1081 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1082
Chris Lattner970e54e2006-11-12 00:37:36 +00001083 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001084 FloatComplexTy = getComplexType(FloatTy);
1085 DoubleComplexTy = getComplexType(DoubleTy);
1086 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001087
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001088 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001089 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1090 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001091 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001092
1093 if (LangOpts.OpenCL) {
1094 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1095 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1096 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1097 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1098 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001099 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1100 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1101 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1102 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1103 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1104 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1105 BuiltinType::OCLImage2dArrayMSAADepth);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001106 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001107
Guy Benyei61054192013-02-07 10:55:47 +00001108 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001109 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001110 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1111 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1112 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1113 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001114 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001115
1116 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001117 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1118 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001119
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001120 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001121
1122 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001123
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001124 // void * type
1125 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001126
1127 // nullptr type (C++0x 2.14.7)
1128 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001129
1130 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1131 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001132
1133 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001134 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001135}
1136
David Blaikie9c902b52011-09-25 23:23:43 +00001137DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001138 return SourceMgr.getDiagnostics();
1139}
1140
Douglas Gregor561eceb2010-08-30 16:49:28 +00001141AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1142 AttrVec *&Result = DeclAttrs[D];
1143 if (!Result) {
1144 void *Mem = Allocate(sizeof(AttrVec));
1145 Result = new (Mem) AttrVec;
1146 }
1147
1148 return *Result;
1149}
1150
1151/// \brief Erase the attributes corresponding to the given declaration.
1152void ASTContext::eraseDeclAttrs(const Decl *D) {
1153 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1154 if (Pos != DeclAttrs.end()) {
1155 Pos->second->~AttrVec();
1156 DeclAttrs.erase(Pos);
1157 }
1158}
1159
Larisse Voufo39a1e502013-08-06 01:03:05 +00001160// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001161MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001162ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001163 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001164 return getTemplateOrSpecializationInfo(Var)
1165 .dyn_cast<MemberSpecializationInfo *>();
1166}
1167
1168ASTContext::TemplateOrSpecializationInfo
1169ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1170 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1171 TemplateOrInstantiation.find(Var);
1172 if (Pos == TemplateOrInstantiation.end())
1173 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001174
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001175 return Pos->second;
1176}
1177
Mike Stump11289f42009-09-09 15:08:12 +00001178void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001179ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001180 TemplateSpecializationKind TSK,
1181 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001182 assert(Inst->isStaticDataMember() && "Not a static data member");
1183 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001184 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1185 Tmpl, TSK, PointOfInstantiation));
1186}
1187
1188void
1189ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1190 TemplateOrSpecializationInfo TSI) {
1191 assert(!TemplateOrInstantiation[Inst] &&
1192 "Already noted what the variable was instantiated from");
1193 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001194}
1195
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001196FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1197 const FunctionDecl *FD){
1198 assert(FD && "Specialization is 0");
1199 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001200 = ClassScopeSpecializationPattern.find(FD);
1201 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001202 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001203
1204 return Pos->second;
1205}
1206
1207void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1208 FunctionDecl *Pattern) {
1209 assert(FD && "Specialization is 0");
1210 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001211 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001212}
1213
John McCalle61f2ba2009-11-18 02:36:19 +00001214NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001215ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001216 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001217 = InstantiatedFromUsingDecl.find(UUD);
1218 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001219 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001220
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001221 return Pos->second;
1222}
1223
1224void
John McCallb96ec562009-12-04 22:46:56 +00001225ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1226 assert((isa<UsingDecl>(Pattern) ||
1227 isa<UnresolvedUsingValueDecl>(Pattern) ||
1228 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1229 "pattern decl is not a using decl");
1230 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1231 InstantiatedFromUsingDecl[Inst] = Pattern;
1232}
1233
1234UsingShadowDecl *
1235ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1236 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1237 = InstantiatedFromUsingShadowDecl.find(Inst);
1238 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001239 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001240
1241 return Pos->second;
1242}
1243
1244void
1245ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1246 UsingShadowDecl *Pattern) {
1247 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1248 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001249}
1250
Anders Carlsson5da84842009-09-01 04:26:58 +00001251FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1252 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1253 = InstantiatedFromUnnamedFieldDecl.find(Field);
1254 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001255 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001256
Anders Carlsson5da84842009-09-01 04:26:58 +00001257 return Pos->second;
1258}
1259
1260void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1261 FieldDecl *Tmpl) {
1262 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1263 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1264 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1265 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001266
Anders Carlsson5da84842009-09-01 04:26:58 +00001267 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1268}
1269
Douglas Gregor832940b2010-03-02 23:58:15 +00001270ASTContext::overridden_cxx_method_iterator
1271ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1272 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001273 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001274 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001275 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001276
1277 return Pos->second.begin();
1278}
1279
1280ASTContext::overridden_cxx_method_iterator
1281ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1282 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001283 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001284 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001285 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001286
1287 return Pos->second.end();
1288}
1289
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001290unsigned
1291ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1292 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001293 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001294 if (Pos == OverriddenMethods.end())
1295 return 0;
1296
1297 return Pos->second.size();
1298}
1299
Douglas Gregor832940b2010-03-02 23:58:15 +00001300void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1301 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001302 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001303 OverriddenMethods[Method].push_back(Overridden);
1304}
1305
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001306void ASTContext::getOverriddenMethods(
1307 const NamedDecl *D,
1308 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001309 assert(D);
1310
1311 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001312 Overridden.append(overridden_methods_begin(CXXMethod),
1313 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001314 return;
1315 }
1316
1317 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1318 if (!Method)
1319 return;
1320
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001321 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1322 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001323 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001324}
1325
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001326void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1327 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1328 assert(!Import->isFromASTFile() && "Non-local import declaration");
1329 if (!FirstLocalImport) {
1330 FirstLocalImport = Import;
1331 LastLocalImport = Import;
1332 return;
1333 }
1334
1335 LastLocalImport->NextLocalImport = Import;
1336 LastLocalImport = Import;
1337}
1338
Chris Lattner53cfe802007-07-18 17:52:12 +00001339//===----------------------------------------------------------------------===//
1340// Type Sizing and Analysis
1341//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001342
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001343/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1344/// scalar floating point type.
1345const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001346 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001347 assert(BT && "Not a floating point type!");
1348 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001349 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001350 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001351 case BuiltinType::Float: return Target->getFloatFormat();
1352 case BuiltinType::Double: return Target->getDoubleFormat();
1353 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001354 }
1355}
1356
Rafael Espindola71eccb32013-08-08 19:53:46 +00001357CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001358 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001359
John McCall94268702010-10-08 18:24:19 +00001360 bool UseAlignAttrOnly = false;
1361 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1362 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001363
John McCall94268702010-10-08 18:24:19 +00001364 // __attribute__((aligned)) can increase or decrease alignment
1365 // *except* on a struct or struct member, where it only increases
1366 // alignment unless 'packed' is also specified.
1367 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001368 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001369 // ignore that possibility; Sema should diagnose it.
1370 if (isa<FieldDecl>(D)) {
1371 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1372 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1373 } else {
1374 UseAlignAttrOnly = true;
1375 }
1376 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001377 else if (isa<FieldDecl>(D))
1378 UseAlignAttrOnly =
1379 D->hasAttr<PackedAttr>() ||
1380 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001381
John McCall4e819612011-01-20 07:57:12 +00001382 // If we're using the align attribute only, just ignore everything
1383 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001384 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001385 // do nothing
1386
John McCall94268702010-10-08 18:24:19 +00001387 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001388 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001389 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001390 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001391 T = RT->getPointeeType();
1392 else
1393 T = getPointerType(RT->getPointeeType());
1394 }
Richard Smithf6d70302014-06-10 23:34:28 +00001395 QualType BaseT = getBaseElementType(T);
1396 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001397 // Adjust alignments of declarations with array type by the
1398 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001399 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001400 unsigned MinWidth = Target->getLargeArrayMinWidth();
1401 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001402 if (isa<VariableArrayType>(arrayType))
1403 Align = std::max(Align, Target->getLargeArrayAlign());
1404 else if (isa<ConstantArrayType>(arrayType) &&
1405 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1406 Align = std::max(Align, Target->getLargeArrayAlign());
1407 }
John McCall33ddac02011-01-19 10:06:00 +00001408 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001409 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001410 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001411 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001412 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1413 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001414 }
John McCall4e819612011-01-20 07:57:12 +00001415
1416 // Fields can be subject to extra alignment constraints, like if
1417 // the field is packed, the struct is packed, or the struct has a
1418 // a max-field-alignment constraint (#pragma pack). So calculate
1419 // the actual alignment of the field within the struct, and then
1420 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001421 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1422 const RecordDecl *Parent = Field->getParent();
1423 // We can only produce a sensible answer if the record is valid.
1424 if (!Parent->isInvalidDecl()) {
1425 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001426
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001427 // Start with the record's overall alignment.
1428 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001429
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001430 // Use the GCD of that and the offset within the record.
1431 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1432 if (Offset > 0) {
1433 // Alignment is always a power of 2, so the GCD will be a power of 2,
1434 // which means we get to do this crazy thing instead of Euclid's.
1435 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1436 if (LowBitOfOffset < FieldAlign)
1437 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1438 }
1439
1440 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001441 }
Charles Davis3fc51072010-02-23 04:52:00 +00001442 }
Chris Lattner68061312009-01-24 21:53:27 +00001443 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001444
Ken Dyckcc56c542011-01-15 18:38:59 +00001445 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001446}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001447
John McCallf1249922012-08-21 04:10:00 +00001448// getTypeInfoDataSizeInChars - Return the size of a type, in
1449// chars. If the type is a record, its data size is returned. This is
1450// the size of the memcpy that's performed when assigning this type
1451// using a trivial copy/move assignment operator.
1452std::pair<CharUnits, CharUnits>
1453ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1454 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1455
1456 // In C++, objects can sometimes be allocated into the tail padding
1457 // of a base-class subobject. We decide whether that's possible
1458 // during class layout, so here we can just trust the layout results.
1459 if (getLangOpts().CPlusPlus) {
1460 if (const RecordType *RT = T->getAs<RecordType>()) {
1461 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1462 sizeAndAlign.first = layout.getDataSize();
1463 }
1464 }
1465
1466 return sizeAndAlign;
1467}
1468
Richard Trieu04d2d942013-05-14 21:59:17 +00001469/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1470/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1471std::pair<CharUnits, CharUnits>
1472static getConstantArrayInfoInChars(const ASTContext &Context,
1473 const ConstantArrayType *CAT) {
1474 std::pair<CharUnits, CharUnits> EltInfo =
1475 Context.getTypeInfoInChars(CAT->getElementType());
1476 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001477 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1478 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001479 "Overflow in array type char size evaluation");
1480 uint64_t Width = EltInfo.first.getQuantity() * Size;
1481 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001482 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1483 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001484 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001485 return std::make_pair(CharUnits::fromQuantity(Width),
1486 CharUnits::fromQuantity(Align));
1487}
1488
John McCall87fe5d52010-05-20 01:18:31 +00001489std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001490ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001491 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1492 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001493 TypeInfo Info = getTypeInfo(T);
1494 return std::make_pair(toCharUnitsFromBits(Info.Width),
1495 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001496}
1497
1498std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001499ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001500 return getTypeInfoInChars(T.getTypePtr());
1501}
1502
David Majnemer34b57492014-07-30 01:30:47 +00001503bool ASTContext::isAlignmentRequired(const Type *T) const {
1504 return getTypeInfo(T).AlignIsRequired;
1505}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001506
David Majnemer34b57492014-07-30 01:30:47 +00001507bool ASTContext::isAlignmentRequired(QualType T) const {
1508 return isAlignmentRequired(T.getTypePtr());
1509}
1510
1511TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001512 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1513 if (I != MemoizedTypeInfo.end())
1514 return I->second;
1515
1516 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1517 TypeInfo TI = getTypeInfoImpl(T);
1518 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001519 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001520}
1521
1522/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1523/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001524///
1525/// FIXME: Pointers into different addr spaces could have different sizes and
1526/// alignment requirements: getPointerInfo should take an AddrSpace, this
1527/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001528TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1529 uint64_t Width = 0;
1530 unsigned Align = 8;
1531 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001532 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001533#define TYPE(Class, Base)
1534#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001535#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001536#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001537#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1538 case Type::Class: \
1539 assert(!T->isDependentType() && "should not see dependent types here"); \
1540 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001541#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001542 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001543
Chris Lattner355332d2007-07-13 22:27:08 +00001544 case Type::FunctionNoProto:
1545 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001546 // GCC extension: alignof(function) = 32 bits
1547 Width = 0;
1548 Align = 32;
1549 break;
1550
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001551 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001552 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001553 Width = 0;
1554 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1555 break;
1556
Steve Naroff5c131802007-08-30 01:06:46 +00001557 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001558 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001559
David Majnemer34b57492014-07-30 01:30:47 +00001560 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001561 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001562 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001563 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001564 Width = EltInfo.Width * Size;
1565 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001566 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1567 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001568 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001569 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001570 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001571 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001572 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001573 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001574 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1575 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001576 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001577 // If the alignment is not a power of 2, round up to the next power of 2.
1578 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001579 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001580 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001581 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001582 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001583 // Adjust the alignment based on the target max.
1584 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1585 if (TargetVectorAlign && TargetVectorAlign < Align)
1586 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001587 break;
1588 }
Chris Lattner647fb222007-07-18 18:26:58 +00001589
Chris Lattner7570e9c2008-03-08 08:52:55 +00001590 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001591 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001592 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001593 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001594 // GCC extension: alignof(void) = 8 bits.
1595 Width = 0;
1596 Align = 8;
1597 break;
1598
Chris Lattner6a4f7452007-12-19 19:23:28 +00001599 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001600 Width = Target->getBoolWidth();
1601 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001602 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001603 case BuiltinType::Char_S:
1604 case BuiltinType::Char_U:
1605 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001606 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001607 Width = Target->getCharWidth();
1608 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001609 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001610 case BuiltinType::WChar_S:
1611 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001612 Width = Target->getWCharWidth();
1613 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001614 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001615 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001616 Width = Target->getChar16Width();
1617 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001618 break;
1619 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001620 Width = Target->getChar32Width();
1621 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001622 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001623 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001624 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001625 Width = Target->getShortWidth();
1626 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001627 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001628 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001629 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001630 Width = Target->getIntWidth();
1631 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001632 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001633 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001634 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001635 Width = Target->getLongWidth();
1636 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001637 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001638 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001639 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001640 Width = Target->getLongLongWidth();
1641 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001642 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001643 case BuiltinType::Int128:
1644 case BuiltinType::UInt128:
1645 Width = 128;
1646 Align = 128; // int128_t is 128-bit aligned on all targets.
1647 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001648 case BuiltinType::Half:
1649 Width = Target->getHalfWidth();
1650 Align = Target->getHalfAlign();
1651 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001652 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001653 Width = Target->getFloatWidth();
1654 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001655 break;
1656 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001657 Width = Target->getDoubleWidth();
1658 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001659 break;
1660 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001661 Width = Target->getLongDoubleWidth();
1662 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001663 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001664 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001665 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1666 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001667 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001668 case BuiltinType::ObjCId:
1669 case BuiltinType::ObjCClass:
1670 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001671 Width = Target->getPointerWidth(0);
1672 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001673 break;
Guy Benyei61054192013-02-07 10:55:47 +00001674 case BuiltinType::OCLSampler:
1675 // Samplers are modeled as integers.
1676 Width = Target->getIntWidth();
1677 Align = Target->getIntAlign();
1678 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001679 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001680 case BuiltinType::OCLClkEvent:
1681 case BuiltinType::OCLQueue:
1682 case BuiltinType::OCLNDRange:
1683 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001684 case BuiltinType::OCLImage1d:
1685 case BuiltinType::OCLImage1dArray:
1686 case BuiltinType::OCLImage1dBuffer:
1687 case BuiltinType::OCLImage2d:
1688 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001689 case BuiltinType::OCLImage2dDepth:
1690 case BuiltinType::OCLImage2dArrayDepth:
1691 case BuiltinType::OCLImage2dMSAA:
1692 case BuiltinType::OCLImage2dArrayMSAA:
1693 case BuiltinType::OCLImage2dMSAADepth:
1694 case BuiltinType::OCLImage2dArrayMSAADepth:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001695 case BuiltinType::OCLImage3d:
1696 // Currently these types are pointers to opaque types.
1697 Width = Target->getPointerWidth(0);
1698 Align = Target->getPointerAlign(0);
1699 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001700 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001701 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001702 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001703 Width = Target->getPointerWidth(0);
1704 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001705 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001706 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001707 unsigned AS = getTargetAddressSpace(
1708 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001709 Width = Target->getPointerWidth(AS);
1710 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001711 break;
1712 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001713 case Type::LValueReference:
1714 case Type::RValueReference: {
1715 // alignof and sizeof should never enter this code path here, so we go
1716 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001717 unsigned AS = getTargetAddressSpace(
1718 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001719 Width = Target->getPointerWidth(AS);
1720 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001721 break;
1722 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001723 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001724 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001725 Width = Target->getPointerWidth(AS);
1726 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001727 break;
1728 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001729 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001730 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001731 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001732 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001733 }
Chris Lattner647fb222007-07-18 18:26:58 +00001734 case Type::Complex: {
1735 // Complex types have the same alignment as their elements, but twice the
1736 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001737 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1738 Width = EltInfo.Width * 2;
1739 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001740 break;
1741 }
John McCall8b07ec22010-05-15 11:32:37 +00001742 case Type::ObjCObject:
1743 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001744 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001745 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001746 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001747 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001748 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001749 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001750 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001751 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001752 break;
1753 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001754 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001755 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001756 const TagType *TT = cast<TagType>(T);
1757
1758 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001759 Width = 8;
1760 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001761 break;
1762 }
Mike Stump11289f42009-09-09 15:08:12 +00001763
David Majnemer475b25e2015-01-21 10:54:38 +00001764 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1765 const EnumDecl *ED = ET->getDecl();
1766 TypeInfo Info =
1767 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1768 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1769 Info.Align = AttrAlign;
1770 Info.AlignIsRequired = true;
1771 }
1772 return Info;
1773 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001774
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001775 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001776 const RecordDecl *RD = RT->getDecl();
1777 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001778 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001779 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001780 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001781 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001782 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001783
Chris Lattner63d2b362009-10-22 05:17:15 +00001784 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001785 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1786 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001787
Richard Smith30482bc2011-02-20 03:19:35 +00001788 case Type::Auto: {
1789 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001790 assert(!A->getDeducedType().isNull() &&
1791 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001792 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001793 }
1794
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001795 case Type::Paren:
1796 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1797
Douglas Gregoref462e62009-04-30 17:32:17 +00001798 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001799 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001800 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001801 // If the typedef has an aligned attribute on it, it overrides any computed
1802 // alignment we have. This violates the GCC documentation (which says that
1803 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001804 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001805 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001806 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001807 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001808 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001809 AlignIsRequired = Info.AlignIsRequired;
1810 }
David Majnemer34b57492014-07-30 01:30:47 +00001811 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001812 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001813 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001814
Abramo Bagnara6150c882010-05-11 21:36:43 +00001815 case Type::Elaborated:
1816 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001817
John McCall81904512011-01-06 01:58:22 +00001818 case Type::Attributed:
1819 return getTypeInfo(
1820 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1821
Eli Friedman0dfb8892011-10-06 23:00:33 +00001822 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001823 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001824 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1825 Width = Info.Width;
1826 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001827
1828 // If the size of the type doesn't exceed the platform's max
1829 // atomic promotion width, make the size and alignment more
1830 // favorable to atomic operations:
1831 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1832 // Round the size up to a power of 2.
1833 if (!llvm::isPowerOf2_64(Width))
1834 Width = llvm::NextPowerOf2(Width);
1835
1836 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001837 Align = static_cast<unsigned>(Width);
1838 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001839 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001840 break;
1841
1842 case Type::Pipe: {
1843 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1844 Width = Info.Width;
1845 Align = Info.Align;
1846 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001847
Douglas Gregoref462e62009-04-30 17:32:17 +00001848 }
Mike Stump11289f42009-09-09 15:08:12 +00001849
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001850 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001851 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001852}
1853
Alexey Bataev00396512015-07-02 03:40:19 +00001854unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1855 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1856 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1857 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1858 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1859 getTargetInfo().getABI() == "elfv1-qpx" &&
1860 T->isSpecificBuiltinType(BuiltinType::Double))
1861 SimdAlign = 256;
1862 return SimdAlign;
1863}
1864
Ken Dyckcc56c542011-01-15 18:38:59 +00001865/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1866CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1867 return CharUnits::fromQuantity(BitSize / getCharWidth());
1868}
1869
Ken Dyckb0fcc592011-02-11 01:54:29 +00001870/// toBits - Convert a size in characters to a size in characters.
1871int64_t ASTContext::toBits(CharUnits CharSize) const {
1872 return CharSize.getQuantity() * getCharWidth();
1873}
1874
Ken Dyck8c89d592009-12-22 14:23:30 +00001875/// getTypeSizeInChars - Return the size of the specified type, in characters.
1876/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001877CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001878 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001879}
Jay Foad39c79802011-01-12 09:06:06 +00001880CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001881 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001882}
1883
Ken Dycka6046ab2010-01-26 17:25:18 +00001884/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001885/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001886CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001887 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001888}
Jay Foad39c79802011-01-12 09:06:06 +00001889CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001890 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001891}
1892
Chris Lattnera3402cd2009-01-27 18:08:34 +00001893/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1894/// type for the current target in bits. This can be different than the ABI
1895/// alignment in cases where it is beneficial for performance to overalign
1896/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001897unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001898 TypeInfo TI = getTypeInfo(T);
1899 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001900
David Majnemere1544562015-04-24 01:25:05 +00001901 T = T->getBaseElementTypeUnsafe();
1902
1903 // The preferred alignment of member pointers is that of a pointer.
1904 if (T->isMemberPointerType())
1905 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1906
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00001907 if (!Target->allowsLargerPreferedTypeAlignment())
1908 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001909
Eli Friedman7ab09572009-05-25 21:27:19 +00001910 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001911 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001912 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001913 if (const EnumType *ET = T->getAs<EnumType>())
1914 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001915 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001916 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1917 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001918 // Don't increase the alignment if an alignment attribute was specified on a
1919 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001920 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001921 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001922
Chris Lattnera3402cd2009-01-27 18:08:34 +00001923 return ABIAlign;
1924}
1925
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001926/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1927/// for __attribute__((aligned)) on this target, to be used if no alignment
1928/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00001929unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001930 return getTargetInfo().getDefaultAlignForAttributeAligned();
1931}
1932
Ulrich Weigandfa806422013-05-06 16:23:57 +00001933/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1934/// to a global variable of the specified type.
1935unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1936 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1937}
1938
1939/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1940/// should be given to a global variable of the specified type.
1941CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1942 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1943}
1944
David Majnemer08ef2ba2015-06-23 20:34:18 +00001945CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1946 CharUnits Offset = CharUnits::Zero();
1947 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1948 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1949 Offset += Layout->getBaseClassOffset(Base);
1950 Layout = &getASTRecordLayout(Base);
1951 }
1952 return Offset;
1953}
1954
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001955/// DeepCollectObjCIvars -
1956/// This routine first collects all declared, but not synthesized, ivars in
1957/// super class and then collects all ivars, including those synthesized for
1958/// current class. This routine is used for implementation of current class
1959/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001960///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001961void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1962 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001963 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001964 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1965 DeepCollectObjCIvars(SuperClass, false, Ivars);
1966 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001967 for (const auto *I : OI->ivars())
1968 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001969 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001970 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001971 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001972 Iv= Iv->getNextIvar())
1973 Ivars.push_back(Iv);
1974 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001975}
1976
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001977/// CollectInheritedProtocols - Collect all protocols in current class and
1978/// those inherited by it.
1979void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001980 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001981 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001982 // We can use protocol_iterator here instead of
1983 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001984 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001985 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001986 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001987
1988 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001989 for (const auto *Cat : OI->visible_categories())
1990 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001991
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001992 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1993 while (SD) {
1994 CollectInheritedProtocols(SD, Protocols);
1995 SD = SD->getSuperClass();
1996 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001997 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001998 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001999 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002000 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002001 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002002 // Insert the protocol.
2003 if (!Protocols.insert(
2004 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2005 return;
2006
2007 for (auto *Proto : OP->protocols())
2008 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002009 }
2010}
2011
Jay Foad39c79802011-01-12 09:06:06 +00002012unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002013 unsigned count = 0;
2014 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002015 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002016 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002017
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002018 // Count ivar defined in this class's implementation. This
2019 // includes synthesized ivars.
2020 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002021 count += ImplDecl->ivar_size();
2022
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002023 return count;
2024}
2025
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002026bool ASTContext::isSentinelNullExpr(const Expr *E) {
2027 if (!E)
2028 return false;
2029
2030 // nullptr_t is always treated as null.
2031 if (E->getType()->isNullPtrType()) return true;
2032
2033 if (E->getType()->isAnyPointerType() &&
2034 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2035 Expr::NPC_ValueDependentIsNull))
2036 return true;
2037
2038 // Unfortunately, __null has type 'int'.
2039 if (isa<GNUNullExpr>(E)) return true;
2040
2041 return false;
2042}
2043
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002044/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2045ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2046 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2047 I = ObjCImpls.find(D);
2048 if (I != ObjCImpls.end())
2049 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002050 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002051}
2052/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2053ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2054 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2055 I = ObjCImpls.find(D);
2056 if (I != ObjCImpls.end())
2057 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002058 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002059}
2060
2061/// \brief Set the implementation of ObjCInterfaceDecl.
2062void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2063 ObjCImplementationDecl *ImplD) {
2064 assert(IFaceD && ImplD && "Passed null params");
2065 ObjCImpls[IFaceD] = ImplD;
2066}
2067/// \brief Set the implementation of ObjCCategoryDecl.
2068void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2069 ObjCCategoryImplDecl *ImplD) {
2070 assert(CatD && ImplD && "Passed null params");
2071 ObjCImpls[CatD] = ImplD;
2072}
2073
Chandler Carruth21c90602015-12-30 03:24:14 +00002074const ObjCMethodDecl *
2075ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2076 return ObjCMethodRedecls.lookup(MD);
2077}
2078
2079void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2080 const ObjCMethodDecl *Redecl) {
2081 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2082 ObjCMethodRedecls[MD] = Redecl;
2083}
2084
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002085const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2086 const NamedDecl *ND) const {
2087 if (const ObjCInterfaceDecl *ID =
2088 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002089 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002090 if (const ObjCCategoryDecl *CD =
2091 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002092 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002093 if (const ObjCImplDecl *IMD =
2094 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002095 return IMD->getClassInterface();
2096
Craig Topper36250ad2014-05-12 05:36:57 +00002097 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002098}
2099
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002100/// \brief Get the copy initialization expression of VarDecl,or NULL if
2101/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002102Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002103 assert(VD && "Passed null params");
2104 assert(VD->hasAttr<BlocksAttr>() &&
2105 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002106 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002107 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002108 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002109}
2110
2111/// \brief Set the copy inialization expression of a block var decl.
2112void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2113 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002114 assert(VD->hasAttr<BlocksAttr>() &&
2115 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002116 BlockVarCopyInits[VD] = Init;
2117}
2118
John McCallbcd03502009-12-07 02:54:59 +00002119TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002120 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002121 if (!DataSize)
2122 DataSize = TypeLoc::getFullDataSizeForType(T);
2123 else
2124 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002125 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002126
John McCallbcd03502009-12-07 02:54:59 +00002127 TypeSourceInfo *TInfo =
2128 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2129 new (TInfo) TypeSourceInfo(T);
2130 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002131}
2132
John McCallbcd03502009-12-07 02:54:59 +00002133TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002134 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002135 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002136 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002137 return DI;
2138}
2139
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002140const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002141ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002142 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002143}
2144
2145const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002146ASTContext::getASTObjCImplementationLayout(
2147 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002148 return getObjCLayout(D->getClassInterface(), D);
2149}
2150
Chris Lattner983a8bb2007-07-13 22:13:22 +00002151//===----------------------------------------------------------------------===//
2152// Type creation/memoization methods
2153//===----------------------------------------------------------------------===//
2154
Jay Foad39c79802011-01-12 09:06:06 +00002155QualType
John McCall33ddac02011-01-19 10:06:00 +00002156ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2157 unsigned fastQuals = quals.getFastQualifiers();
2158 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002159
2160 // Check if we've already instantiated this type.
2161 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002162 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002163 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002164 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2165 assert(eq->getQualifiers() == quals);
2166 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002167 }
2168
John McCall33ddac02011-01-19 10:06:00 +00002169 // If the base type is not canonical, make the appropriate canonical type.
2170 QualType canon;
2171 if (!baseType->isCanonicalUnqualified()) {
2172 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002173 canonSplit.Quals.addConsistentQualifiers(quals);
2174 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002175
2176 // Re-find the insert position.
2177 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2178 }
2179
2180 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2181 ExtQualNodes.InsertNode(eq, insertPos);
2182 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002183}
2184
Jay Foad39c79802011-01-12 09:06:06 +00002185QualType
2186ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002187 QualType CanT = getCanonicalType(T);
2188 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002189 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002190
John McCall8ccfcb52009-09-24 19:53:00 +00002191 // If we are composing extended qualifiers together, merge together
2192 // into one ExtQuals node.
2193 QualifierCollector Quals;
2194 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002195
John McCall8ccfcb52009-09-24 19:53:00 +00002196 // If this type already has an address space specified, it cannot get
2197 // another one.
2198 assert(!Quals.hasAddressSpace() &&
2199 "Type cannot be in multiple addr spaces!");
2200 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002201
John McCall8ccfcb52009-09-24 19:53:00 +00002202 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002203}
2204
Chris Lattnerd60183d2009-02-18 22:53:11 +00002205QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002206 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002207 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002208 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002209 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002210
John McCall53fa7142010-12-24 02:08:15 +00002211 if (const PointerType *ptr = T->getAs<PointerType>()) {
2212 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002213 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002214 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2215 return getPointerType(ResultType);
2216 }
2217 }
Mike Stump11289f42009-09-09 15:08:12 +00002218
John McCall8ccfcb52009-09-24 19:53:00 +00002219 // If we are composing extended qualifiers together, merge together
2220 // into one ExtQuals node.
2221 QualifierCollector Quals;
2222 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002223
John McCall8ccfcb52009-09-24 19:53:00 +00002224 // If this type already has an ObjCGC specified, it cannot get
2225 // another one.
2226 assert(!Quals.hasObjCGCAttr() &&
2227 "Type cannot have multiple ObjCGCs!");
2228 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002229
John McCall8ccfcb52009-09-24 19:53:00 +00002230 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002231}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002232
John McCall4f5019e2010-12-19 02:44:49 +00002233const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2234 FunctionType::ExtInfo Info) {
2235 if (T->getExtInfo() == Info)
2236 return T;
2237
2238 QualType Result;
2239 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002240 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002241 } else {
2242 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2243 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2244 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002245 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002246 }
2247
2248 return cast<FunctionType>(Result.getTypePtr());
2249}
2250
Richard Smith2a7d4812013-05-04 07:00:32 +00002251void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2252 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002253 FD = FD->getMostRecentDecl();
2254 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002255 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2256 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002257 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002258 if (FunctionDecl *Next = FD->getPreviousDecl())
2259 FD = Next;
2260 else
2261 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002262 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002263 if (ASTMutationListener *L = getASTMutationListener())
2264 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002265}
2266
Richard Smith0b3a4622014-11-13 20:01:57 +00002267/// Get a function type and produce the equivalent function type with the
2268/// specified exception specification. Type sugar that can be present on a
2269/// declaration of a function with an exception specification is permitted
2270/// and preserved. Other type sugar (for instance, typedefs) is not.
2271static QualType getFunctionTypeWithExceptionSpec(
2272 ASTContext &Context, QualType Orig,
2273 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2274 // Might have some parens.
2275 if (auto *PT = dyn_cast<ParenType>(Orig))
2276 return Context.getParenType(
2277 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2278
2279 // Might have a calling-convention attribute.
2280 if (auto *AT = dyn_cast<AttributedType>(Orig))
2281 return Context.getAttributedType(
2282 AT->getAttrKind(),
2283 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2284 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2285 ESI));
2286
2287 // Anything else must be a function type. Rebuild it with the new exception
2288 // specification.
2289 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2290 return Context.getFunctionType(
2291 Proto->getReturnType(), Proto->getParamTypes(),
2292 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2293}
2294
2295void ASTContext::adjustExceptionSpec(
2296 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2297 bool AsWritten) {
2298 // Update the type.
2299 QualType Updated =
2300 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2301 FD->setType(Updated);
2302
2303 if (!AsWritten)
2304 return;
2305
2306 // Update the type in the type source information too.
2307 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2308 // If the type and the type-as-written differ, we may need to update
2309 // the type-as-written too.
2310 if (TSInfo->getType() != FD->getType())
2311 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2312
2313 // FIXME: When we get proper type location information for exceptions,
2314 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2315 // up the TypeSourceInfo;
2316 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2317 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2318 "TypeLoc size mismatch from updating exception specification");
2319 TSInfo->overrideType(Updated);
2320 }
2321}
2322
Chris Lattnerc6395932007-06-22 20:56:16 +00002323/// getComplexType - Return the uniqued reference to the type for a complex
2324/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002325QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002326 // Unique pointers, to guarantee there is only one pointer of a particular
2327 // structure.
2328 llvm::FoldingSetNodeID ID;
2329 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002330
Craig Topper36250ad2014-05-12 05:36:57 +00002331 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002332 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2333 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002334
Chris Lattnerc6395932007-06-22 20:56:16 +00002335 // If the pointee type isn't canonical, this won't be a canonical type either,
2336 // so fill in the canonical type field.
2337 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002338 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002339 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002340
Chris Lattnerc6395932007-06-22 20:56:16 +00002341 // Get the new insert position for the node we care about.
2342 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002343 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002344 }
John McCall90d1c2d2009-09-24 23:30:46 +00002345 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002346 Types.push_back(New);
2347 ComplexTypes.InsertNode(New, InsertPos);
2348 return QualType(New, 0);
2349}
2350
Chris Lattner970e54e2006-11-12 00:37:36 +00002351/// getPointerType - Return the uniqued reference to the type for a pointer to
2352/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002353QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002354 // Unique pointers, to guarantee there is only one pointer of a particular
2355 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002356 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002357 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002358
Craig Topper36250ad2014-05-12 05:36:57 +00002359 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002360 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002361 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002362
Chris Lattner7ccecb92006-11-12 08:50:50 +00002363 // If the pointee type isn't canonical, this won't be a canonical type either,
2364 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002365 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002366 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002367 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002368
Bob Wilsonc8541f22013-03-15 17:12:43 +00002369 // Get the new insert position for the node we care about.
2370 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002371 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002372 }
John McCall90d1c2d2009-09-24 23:30:46 +00002373 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002374 Types.push_back(New);
2375 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002376 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002377}
2378
Reid Kleckner0503a872013-12-05 01:23:43 +00002379QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2380 llvm::FoldingSetNodeID ID;
2381 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002382 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002383 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2384 if (AT)
2385 return QualType(AT, 0);
2386
2387 QualType Canonical = getCanonicalType(New);
2388
2389 // Get the new insert position for the node we care about.
2390 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002391 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002392
2393 AT = new (*this, TypeAlignment)
2394 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2395 Types.push_back(AT);
2396 AdjustedTypes.InsertNode(AT, InsertPos);
2397 return QualType(AT, 0);
2398}
2399
Reid Kleckner8a365022013-06-24 17:51:48 +00002400QualType ASTContext::getDecayedType(QualType T) const {
2401 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2402
Reid Kleckner8a365022013-06-24 17:51:48 +00002403 QualType Decayed;
2404
2405 // C99 6.7.5.3p7:
2406 // A declaration of a parameter as "array of type" shall be
2407 // adjusted to "qualified pointer to type", where the type
2408 // qualifiers (if any) are those specified within the [ and ] of
2409 // the array type derivation.
2410 if (T->isArrayType())
2411 Decayed = getArrayDecayedType(T);
2412
2413 // C99 6.7.5.3p8:
2414 // A declaration of a parameter as "function returning type"
2415 // shall be adjusted to "pointer to function returning type", as
2416 // in 6.3.2.1.
2417 if (T->isFunctionType())
2418 Decayed = getPointerType(T);
2419
Reid Kleckner0503a872013-12-05 01:23:43 +00002420 llvm::FoldingSetNodeID ID;
2421 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002422 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002423 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2424 if (AT)
2425 return QualType(AT, 0);
2426
Reid Kleckner8a365022013-06-24 17:51:48 +00002427 QualType Canonical = getCanonicalType(Decayed);
2428
2429 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002430 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002431 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002432
Reid Kleckner0503a872013-12-05 01:23:43 +00002433 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2434 Types.push_back(AT);
2435 AdjustedTypes.InsertNode(AT, InsertPos);
2436 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002437}
2438
Mike Stump11289f42009-09-09 15:08:12 +00002439/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002440/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002441QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002442 assert(T->isFunctionType() && "block of function types only");
2443 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002444 // structure.
2445 llvm::FoldingSetNodeID ID;
2446 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002447
Craig Topper36250ad2014-05-12 05:36:57 +00002448 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002449 if (BlockPointerType *PT =
2450 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2451 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002452
2453 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002454 // type either so fill in the canonical type field.
2455 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002456 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002457 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002458
Steve Naroffec33ed92008-08-27 16:04:49 +00002459 // Get the new insert position for the node we care about.
2460 BlockPointerType *NewIP =
2461 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002462 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002463 }
John McCall90d1c2d2009-09-24 23:30:46 +00002464 BlockPointerType *New
2465 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002466 Types.push_back(New);
2467 BlockPointerTypes.InsertNode(New, InsertPos);
2468 return QualType(New, 0);
2469}
2470
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002471/// getLValueReferenceType - Return the uniqued reference to the type for an
2472/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002473QualType
2474ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002475 assert(getCanonicalType(T) != OverloadTy &&
2476 "Unresolved overloaded function type");
2477
Bill Wendling3708c182007-05-27 10:15:43 +00002478 // Unique pointers, to guarantee there is only one pointer of a particular
2479 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002480 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002481 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002482
Craig Topper36250ad2014-05-12 05:36:57 +00002483 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002484 if (LValueReferenceType *RT =
2485 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002486 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002487
John McCallfc93cf92009-10-22 22:37:11 +00002488 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2489
Bill Wendling3708c182007-05-27 10:15:43 +00002490 // If the referencee type isn't canonical, this won't be a canonical type
2491 // either, so fill in the canonical type field.
2492 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002493 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2494 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2495 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002496
Bill Wendling3708c182007-05-27 10:15:43 +00002497 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002498 LValueReferenceType *NewIP =
2499 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002500 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002501 }
2502
John McCall90d1c2d2009-09-24 23:30:46 +00002503 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002504 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2505 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002506 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002507 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002508
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002509 return QualType(New, 0);
2510}
2511
2512/// getRValueReferenceType - Return the uniqued reference to the type for an
2513/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002514QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002515 // Unique pointers, to guarantee there is only one pointer of a particular
2516 // structure.
2517 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002518 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002519
Craig Topper36250ad2014-05-12 05:36:57 +00002520 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002521 if (RValueReferenceType *RT =
2522 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2523 return QualType(RT, 0);
2524
John McCallfc93cf92009-10-22 22:37:11 +00002525 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2526
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002527 // If the referencee type isn't canonical, this won't be a canonical type
2528 // either, so fill in the canonical type field.
2529 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002530 if (InnerRef || !T.isCanonical()) {
2531 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2532 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002533
2534 // Get the new insert position for the node we care about.
2535 RValueReferenceType *NewIP =
2536 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002537 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002538 }
2539
John McCall90d1c2d2009-09-24 23:30:46 +00002540 RValueReferenceType *New
2541 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002542 Types.push_back(New);
2543 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002544 return QualType(New, 0);
2545}
2546
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002547/// getMemberPointerType - Return the uniqued reference to the type for a
2548/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002549QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002550 // Unique pointers, to guarantee there is only one pointer of a particular
2551 // structure.
2552 llvm::FoldingSetNodeID ID;
2553 MemberPointerType::Profile(ID, T, Cls);
2554
Craig Topper36250ad2014-05-12 05:36:57 +00002555 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002556 if (MemberPointerType *PT =
2557 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2558 return QualType(PT, 0);
2559
2560 // If the pointee or class type isn't canonical, this won't be a canonical
2561 // type either, so fill in the canonical type field.
2562 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002563 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002564 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2565
2566 // Get the new insert position for the node we care about.
2567 MemberPointerType *NewIP =
2568 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002569 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002570 }
John McCall90d1c2d2009-09-24 23:30:46 +00002571 MemberPointerType *New
2572 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002573 Types.push_back(New);
2574 MemberPointerTypes.InsertNode(New, InsertPos);
2575 return QualType(New, 0);
2576}
2577
Mike Stump11289f42009-09-09 15:08:12 +00002578/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002579/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002580QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002581 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002582 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002583 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002584 assert((EltTy->isDependentType() ||
2585 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002586 "Constant array of VLAs is illegal!");
2587
Chris Lattnere2df3f92009-05-13 04:12:56 +00002588 // Convert the array size into a canonical width matching the pointer size for
2589 // the target.
2590 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002591 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002592 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002593
Chris Lattner23b7eb62007-06-15 23:05:46 +00002594 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002595 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002596
Craig Topper36250ad2014-05-12 05:36:57 +00002597 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002598 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002599 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002600 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002601
John McCall33ddac02011-01-19 10:06:00 +00002602 // If the element type isn't canonical or has qualifiers, this won't
2603 // be a canonical type either, so fill in the canonical type field.
2604 QualType Canon;
2605 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2606 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002607 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002608 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002609 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002610
Chris Lattner36f8e652007-01-27 08:31:04 +00002611 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002612 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002613 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002614 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002615 }
Mike Stump11289f42009-09-09 15:08:12 +00002616
John McCall90d1c2d2009-09-24 23:30:46 +00002617 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002618 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002619 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002620 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002621 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002622}
2623
John McCall06549462011-01-18 08:40:38 +00002624/// getVariableArrayDecayedType - Turns the given type, which may be
2625/// variably-modified, into the corresponding type with all the known
2626/// sizes replaced with [*].
2627QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2628 // Vastly most common case.
2629 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002630
John McCall06549462011-01-18 08:40:38 +00002631 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002632
John McCall06549462011-01-18 08:40:38 +00002633 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002634 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002635 switch (ty->getTypeClass()) {
2636#define TYPE(Class, Base)
2637#define ABSTRACT_TYPE(Class, Base)
2638#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2639#include "clang/AST/TypeNodes.def"
2640 llvm_unreachable("didn't desugar past all non-canonical types?");
2641
2642 // These types should never be variably-modified.
2643 case Type::Builtin:
2644 case Type::Complex:
2645 case Type::Vector:
2646 case Type::ExtVector:
2647 case Type::DependentSizedExtVector:
2648 case Type::ObjCObject:
2649 case Type::ObjCInterface:
2650 case Type::ObjCObjectPointer:
2651 case Type::Record:
2652 case Type::Enum:
2653 case Type::UnresolvedUsing:
2654 case Type::TypeOfExpr:
2655 case Type::TypeOf:
2656 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002657 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002658 case Type::DependentName:
2659 case Type::InjectedClassName:
2660 case Type::TemplateSpecialization:
2661 case Type::DependentTemplateSpecialization:
2662 case Type::TemplateTypeParm:
2663 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002664 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002665 case Type::PackExpansion:
2666 llvm_unreachable("type should never be variably-modified");
2667
2668 // These types can be variably-modified but should never need to
2669 // further decay.
2670 case Type::FunctionNoProto:
2671 case Type::FunctionProto:
2672 case Type::BlockPointer:
2673 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002674 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002675 return type;
2676
2677 // These types can be variably-modified. All these modifications
2678 // preserve structure except as noted by comments.
2679 // TODO: if we ever care about optimizing VLAs, there are no-op
2680 // optimizations available here.
2681 case Type::Pointer:
2682 result = getPointerType(getVariableArrayDecayedType(
2683 cast<PointerType>(ty)->getPointeeType()));
2684 break;
2685
2686 case Type::LValueReference: {
2687 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2688 result = getLValueReferenceType(
2689 getVariableArrayDecayedType(lv->getPointeeType()),
2690 lv->isSpelledAsLValue());
2691 break;
2692 }
2693
2694 case Type::RValueReference: {
2695 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2696 result = getRValueReferenceType(
2697 getVariableArrayDecayedType(lv->getPointeeType()));
2698 break;
2699 }
2700
Eli Friedman0dfb8892011-10-06 23:00:33 +00002701 case Type::Atomic: {
2702 const AtomicType *at = cast<AtomicType>(ty);
2703 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2704 break;
2705 }
2706
John McCall06549462011-01-18 08:40:38 +00002707 case Type::ConstantArray: {
2708 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2709 result = getConstantArrayType(
2710 getVariableArrayDecayedType(cat->getElementType()),
2711 cat->getSize(),
2712 cat->getSizeModifier(),
2713 cat->getIndexTypeCVRQualifiers());
2714 break;
2715 }
2716
2717 case Type::DependentSizedArray: {
2718 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2719 result = getDependentSizedArrayType(
2720 getVariableArrayDecayedType(dat->getElementType()),
2721 dat->getSizeExpr(),
2722 dat->getSizeModifier(),
2723 dat->getIndexTypeCVRQualifiers(),
2724 dat->getBracketsRange());
2725 break;
2726 }
2727
2728 // Turn incomplete types into [*] types.
2729 case Type::IncompleteArray: {
2730 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2731 result = getVariableArrayType(
2732 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002733 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002734 ArrayType::Normal,
2735 iat->getIndexTypeCVRQualifiers(),
2736 SourceRange());
2737 break;
2738 }
2739
2740 // Turn VLA types into [*] types.
2741 case Type::VariableArray: {
2742 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2743 result = getVariableArrayType(
2744 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002745 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002746 ArrayType::Star,
2747 vat->getIndexTypeCVRQualifiers(),
2748 vat->getBracketsRange());
2749 break;
2750 }
2751 }
2752
2753 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002754 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002755}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002756
Steve Naroffcadebd02007-08-30 18:14:25 +00002757/// getVariableArrayType - Returns a non-unique reference to the type for a
2758/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002759QualType ASTContext::getVariableArrayType(QualType EltTy,
2760 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002761 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002762 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002763 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002764 // Since we don't unique expressions, it isn't possible to unique VLA's
2765 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002766 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002767
John McCall33ddac02011-01-19 10:06:00 +00002768 // Be sure to pull qualifiers off the element type.
2769 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2770 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002771 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002772 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002773 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002774 }
2775
John McCall90d1c2d2009-09-24 23:30:46 +00002776 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002777 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002778
2779 VariableArrayTypes.push_back(New);
2780 Types.push_back(New);
2781 return QualType(New, 0);
2782}
2783
Douglas Gregor4619e432008-12-05 23:32:09 +00002784/// getDependentSizedArrayType - Returns a non-unique reference to
2785/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002786/// type.
John McCall33ddac02011-01-19 10:06:00 +00002787QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2788 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002789 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002790 unsigned elementTypeQuals,
2791 SourceRange brackets) const {
2792 assert((!numElements || numElements->isTypeDependent() ||
2793 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002794 "Size must be type- or value-dependent!");
2795
John McCall33ddac02011-01-19 10:06:00 +00002796 // Dependently-sized array types that do not have a specified number
2797 // of elements will have their sizes deduced from a dependent
2798 // initializer. We do no canonicalization here at all, which is okay
2799 // because they can't be used in most locations.
2800 if (!numElements) {
2801 DependentSizedArrayType *newType
2802 = new (*this, TypeAlignment)
2803 DependentSizedArrayType(*this, elementType, QualType(),
2804 numElements, ASM, elementTypeQuals,
2805 brackets);
2806 Types.push_back(newType);
2807 return QualType(newType, 0);
2808 }
2809
2810 // Otherwise, we actually build a new type every time, but we
2811 // also build a canonical type.
2812
2813 SplitQualType canonElementType = getCanonicalType(elementType).split();
2814
Craig Topper36250ad2014-05-12 05:36:57 +00002815 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002816 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002817 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002818 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002819 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002820
John McCall33ddac02011-01-19 10:06:00 +00002821 // Look for an existing type with these properties.
2822 DependentSizedArrayType *canonTy =
2823 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002824
John McCall33ddac02011-01-19 10:06:00 +00002825 // If we don't have one, build one.
2826 if (!canonTy) {
2827 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002828 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002829 QualType(), numElements, ASM, elementTypeQuals,
2830 brackets);
2831 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2832 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002833 }
2834
John McCall33ddac02011-01-19 10:06:00 +00002835 // Apply qualifiers from the element type to the array.
2836 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002837 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002838
David Majnemer16a74702015-07-24 05:54:19 +00002839 // If we didn't need extra canonicalization for the element type or the size
2840 // expression, then just use that as our result.
2841 if (QualType(canonElementType.Ty, 0) == elementType &&
2842 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002843 return canon;
2844
2845 // Otherwise, we need to build a type which follows the spelling
2846 // of the element type.
2847 DependentSizedArrayType *sugaredType
2848 = new (*this, TypeAlignment)
2849 DependentSizedArrayType(*this, elementType, canon, numElements,
2850 ASM, elementTypeQuals, brackets);
2851 Types.push_back(sugaredType);
2852 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002853}
2854
John McCall33ddac02011-01-19 10:06:00 +00002855QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002856 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002857 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002858 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002859 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002860
Craig Topper36250ad2014-05-12 05:36:57 +00002861 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002862 if (IncompleteArrayType *iat =
2863 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2864 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002865
2866 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002867 // either, so fill in the canonical type field. We also have to pull
2868 // qualifiers off the element type.
2869 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002870
John McCall33ddac02011-01-19 10:06:00 +00002871 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2872 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002873 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002874 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002875 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002876
2877 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002878 IncompleteArrayType *existing =
2879 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2880 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002881 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002882
John McCall33ddac02011-01-19 10:06:00 +00002883 IncompleteArrayType *newType = new (*this, TypeAlignment)
2884 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002885
John McCall33ddac02011-01-19 10:06:00 +00002886 IncompleteArrayTypes.InsertNode(newType, insertPos);
2887 Types.push_back(newType);
2888 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002889}
2890
Steve Naroff91fcddb2007-07-18 18:00:27 +00002891/// getVectorType - Return the unique reference to a vector type of
2892/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002893QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002894 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002895 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002896
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002897 // Check if we've already instantiated a vector of this type.
2898 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002899 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002900
Craig Topper36250ad2014-05-12 05:36:57 +00002901 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002902 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2903 return QualType(VTP, 0);
2904
2905 // If the element type isn't canonical, this won't be a canonical type either,
2906 // so fill in the canonical type field.
2907 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002908 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002909 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002910
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002911 // Get the new insert position for the node we care about.
2912 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002913 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002914 }
John McCall90d1c2d2009-09-24 23:30:46 +00002915 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002916 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002917 VectorTypes.InsertNode(New, InsertPos);
2918 Types.push_back(New);
2919 return QualType(New, 0);
2920}
2921
Nate Begemance4d7fc2008-04-18 23:10:10 +00002922/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002923/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002924QualType
2925ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002926 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002927
Steve Naroff91fcddb2007-07-18 18:00:27 +00002928 // Check if we've already instantiated a vector of this type.
2929 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002930 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002931 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002932 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002933 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2934 return QualType(VTP, 0);
2935
2936 // If the element type isn't canonical, this won't be a canonical type either,
2937 // so fill in the canonical type field.
2938 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002939 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002940 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002941
Steve Naroff91fcddb2007-07-18 18:00:27 +00002942 // Get the new insert position for the node we care about.
2943 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002944 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002945 }
John McCall90d1c2d2009-09-24 23:30:46 +00002946 ExtVectorType *New = new (*this, TypeAlignment)
2947 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002948 VectorTypes.InsertNode(New, InsertPos);
2949 Types.push_back(New);
2950 return QualType(New, 0);
2951}
2952
Jay Foad39c79802011-01-12 09:06:06 +00002953QualType
2954ASTContext::getDependentSizedExtVectorType(QualType vecType,
2955 Expr *SizeExpr,
2956 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002957 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002958 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002959 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002960
Craig Topper36250ad2014-05-12 05:36:57 +00002961 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002962 DependentSizedExtVectorType *Canon
2963 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2964 DependentSizedExtVectorType *New;
2965 if (Canon) {
2966 // We already have a canonical version of this array type; use it as
2967 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002968 New = new (*this, TypeAlignment)
2969 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2970 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002971 } else {
2972 QualType CanonVecTy = getCanonicalType(vecType);
2973 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002974 New = new (*this, TypeAlignment)
2975 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2976 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002977
2978 DependentSizedExtVectorType *CanonCheck
2979 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2980 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2981 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002982 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2983 } else {
2984 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2985 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002986 New = new (*this, TypeAlignment)
2987 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002988 }
2989 }
Mike Stump11289f42009-09-09 15:08:12 +00002990
Douglas Gregor758a8692009-06-17 21:51:59 +00002991 Types.push_back(New);
2992 return QualType(New, 0);
2993}
2994
John McCall18afab72016-03-01 00:49:02 +00002995/// \brief Determine whether \p T is canonical as the result type of a function.
2996static bool isCanonicalResultType(QualType T) {
2997 return T.isCanonical() &&
2998 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2999 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3000}
3001
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003002/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003003///
Jay Foad39c79802011-01-12 09:06:06 +00003004QualType
3005ASTContext::getFunctionNoProtoType(QualType ResultTy,
3006 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003007 // Unique functions, to guarantee there is only one function of a particular
3008 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003009 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003010 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003011
Craig Topper36250ad2014-05-12 05:36:57 +00003012 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003013 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003014 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003015 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003016
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003017 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003018 if (!isCanonicalResultType(ResultTy)) {
3019 Canonical =
3020 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003021
Chris Lattner47955de2007-01-27 08:37:20 +00003022 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003023 FunctionNoProtoType *NewIP =
3024 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003025 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003026 }
Mike Stump11289f42009-09-09 15:08:12 +00003027
John McCall90d1c2d2009-09-24 23:30:46 +00003028 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003029 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003030 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003031 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003032 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003033}
3034
Douglas Gregora602a152015-10-01 20:20:47 +00003035CanQualType
3036ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3037 CanQualType CanResultType = getCanonicalType(ResultType);
3038
3039 // Canonical result types do not have ARC lifetime qualifiers.
3040 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3041 Qualifiers Qs = CanResultType.getQualifiers();
3042 Qs.removeObjCLifetime();
3043 return CanQualType::CreateUnsafe(
3044 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3045 }
3046
3047 return CanResultType;
3048}
3049
Jay Foad39c79802011-01-12 09:06:06 +00003050QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003051ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003052 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003053 size_t NumArgs = ArgArray.size();
3054
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003055 // Unique functions, to guarantee there is only one function of a particular
3056 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003057 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003058 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3059 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003060
Craig Topper36250ad2014-05-12 05:36:57 +00003061 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003062 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003063 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003064 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003065
3066 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003067 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003068 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003069 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003070 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003071 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003072 isCanonical = false;
3073
3074 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003075 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003076 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003077 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003078 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003079 CanonicalArgs.reserve(NumArgs);
3080 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003081 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003082
John McCalldb40c7f2010-12-14 08:05:40 +00003083 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003084 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003085 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003086
Douglas Gregora602a152015-10-01 20:20:47 +00003087 // Adjust the canonical function result type.
3088 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003089 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003090
Chris Lattnerfd4de792007-01-27 01:15:32 +00003091 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003092 FunctionProtoType *NewIP =
3093 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003094 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003095 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003096
John McCall31168b02011-06-15 23:02:42 +00003097 // FunctionProtoType objects are allocated with extra bytes after
3098 // them for three variable size arrays at the end:
3099 // - parameter types
3100 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003101 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003102 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003103 // expression, or information used to resolve the exception
3104 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003105 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003106 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003107
Richard Smith8acb4282014-07-31 21:57:55 +00003108 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3109 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3110 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003111 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003112 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003113 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003114 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003115 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003116 }
John McCall18afab72016-03-01 00:49:02 +00003117
3118 // Put the ExtParameterInfos last. If all were equal, it would make
3119 // more sense to put these before the exception specification, because
3120 // it's much easier to skip past them compared to the elaborate switch
3121 // required to skip the exception specification. However, all is not
3122 // equal; ExtParameterInfos are used to model very uncommon features,
3123 // and it's better not to burden the more common paths.
3124 if (EPI.ExtParameterInfos) {
3125 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3126 }
John McCall31168b02011-06-15 23:02:42 +00003127
John McCalldb40c7f2010-12-14 08:05:40 +00003128 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003129 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003130 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003131 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003132 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003133 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003134}
Chris Lattneref51c202006-11-10 07:17:23 +00003135
Xiuli Pan9c14e282016-01-09 12:53:17 +00003136/// Return pipe type for the specified type.
3137QualType ASTContext::getPipeType(QualType T) const {
3138 llvm::FoldingSetNodeID ID;
3139 PipeType::Profile(ID, T);
3140
3141 void *InsertPos = 0;
3142 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3143 return QualType(PT, 0);
3144
3145 // If the pipe element type isn't canonical, this won't be a canonical type
3146 // either, so fill in the canonical type field.
3147 QualType Canonical;
3148 if (!T.isCanonical()) {
3149 Canonical = getPipeType(getCanonicalType(T));
3150
3151 // Get the new insert position for the node we care about.
3152 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3153 assert(!NewIP && "Shouldn't be in the map!");
3154 (void)NewIP;
3155 }
3156 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3157 Types.push_back(New);
3158 PipeTypes.InsertNode(New, InsertPos);
3159 return QualType(New, 0);
3160}
3161
John McCalle78aac42010-03-10 03:28:59 +00003162#ifndef NDEBUG
3163static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3164 if (!isa<CXXRecordDecl>(D)) return false;
3165 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3166 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3167 return true;
3168 if (RD->getDescribedClassTemplate() &&
3169 !isa<ClassTemplateSpecializationDecl>(RD))
3170 return true;
3171 return false;
3172}
3173#endif
3174
3175/// getInjectedClassNameType - Return the unique reference to the
3176/// injected class name type for the specified templated declaration.
3177QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003178 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003179 assert(NeedsInjectedClassNameType(Decl));
3180 if (Decl->TypeForDecl) {
3181 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003182 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003183 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3184 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3185 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3186 } else {
John McCall424cec92011-01-19 06:33:43 +00003187 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003188 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003189 Decl->TypeForDecl = newType;
3190 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003191 }
3192 return QualType(Decl->TypeForDecl, 0);
3193}
3194
Douglas Gregor83a586e2008-04-13 21:07:44 +00003195/// getTypeDeclType - Return the unique reference to the type for the
3196/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003197QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003198 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003199 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003200
Richard Smithdda56e42011-04-15 14:24:37 +00003201 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003202 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003203
John McCall96f0b5f2010-03-10 06:48:02 +00003204 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3205 "Template type parameter types are always available.");
3206
John McCall81e38502010-02-16 03:57:14 +00003207 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003208 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003209 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003210 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003211 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003212 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003213 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003214 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003215 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003216 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3217 Decl->TypeForDecl = newType;
3218 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003219 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003220 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003221
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003222 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003223}
3224
Chris Lattner32d920b2007-01-26 02:01:53 +00003225/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003226/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003227QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003228ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3229 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003230 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003231
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003232 if (Canonical.isNull())
3233 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003234 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003235 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003236 Decl->TypeForDecl = newType;
3237 Types.push_back(newType);
3238 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003239}
3240
Jay Foad39c79802011-01-12 09:06:06 +00003241QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003242 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3243
Douglas Gregorec9fd132012-01-14 16:38:05 +00003244 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003245 if (PrevDecl->TypeForDecl)
3246 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3247
John McCall424cec92011-01-19 06:33:43 +00003248 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3249 Decl->TypeForDecl = newType;
3250 Types.push_back(newType);
3251 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003252}
3253
Jay Foad39c79802011-01-12 09:06:06 +00003254QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003255 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3256
Douglas Gregorec9fd132012-01-14 16:38:05 +00003257 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003258 if (PrevDecl->TypeForDecl)
3259 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3260
John McCall424cec92011-01-19 06:33:43 +00003261 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3262 Decl->TypeForDecl = newType;
3263 Types.push_back(newType);
3264 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003265}
3266
John McCall81904512011-01-06 01:58:22 +00003267QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3268 QualType modifiedType,
3269 QualType equivalentType) {
3270 llvm::FoldingSetNodeID id;
3271 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3272
Craig Topper36250ad2014-05-12 05:36:57 +00003273 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003274 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3275 if (type) return QualType(type, 0);
3276
3277 QualType canon = getCanonicalType(equivalentType);
3278 type = new (*this, TypeAlignment)
3279 AttributedType(canon, attrKind, modifiedType, equivalentType);
3280
3281 Types.push_back(type);
3282 AttributedTypes.InsertNode(type, insertPos);
3283
3284 return QualType(type, 0);
3285}
3286
John McCallcebee162009-10-18 09:09:24 +00003287/// \brief Retrieve a substitution-result type.
3288QualType
3289ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003290 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003291 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003292 && "replacement types must always be canonical");
3293
3294 llvm::FoldingSetNodeID ID;
3295 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003296 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003297 SubstTemplateTypeParmType *SubstParm
3298 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3299
3300 if (!SubstParm) {
3301 SubstParm = new (*this, TypeAlignment)
3302 SubstTemplateTypeParmType(Parm, Replacement);
3303 Types.push_back(SubstParm);
3304 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3305 }
3306
3307 return QualType(SubstParm, 0);
3308}
3309
Douglas Gregorada4b792011-01-14 02:55:32 +00003310/// \brief Retrieve a
3311QualType ASTContext::getSubstTemplateTypeParmPackType(
3312 const TemplateTypeParmType *Parm,
3313 const TemplateArgument &ArgPack) {
3314#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003315 for (const auto &P : ArgPack.pack_elements()) {
3316 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3317 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003318 }
3319#endif
3320
3321 llvm::FoldingSetNodeID ID;
3322 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003323 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003324 if (SubstTemplateTypeParmPackType *SubstParm
3325 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3326 return QualType(SubstParm, 0);
3327
3328 QualType Canon;
3329 if (!Parm->isCanonicalUnqualified()) {
3330 Canon = getCanonicalType(QualType(Parm, 0));
3331 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3332 ArgPack);
3333 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3334 }
3335
3336 SubstTemplateTypeParmPackType *SubstParm
3337 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3338 ArgPack);
3339 Types.push_back(SubstParm);
3340 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3341 return QualType(SubstParm, 0);
3342}
3343
Douglas Gregoreff93e02009-02-05 23:33:38 +00003344/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003345/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003346/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003347QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003348 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003349 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003350 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003351 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003352 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003353 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003354 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3355
3356 if (TypeParm)
3357 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003358
Chandler Carruth08836322011-05-01 00:51:33 +00003359 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003360 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003361 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003362
3363 TemplateTypeParmType *TypeCheck
3364 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3365 assert(!TypeCheck && "Template type parameter canonical type broken");
3366 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003367 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003368 TypeParm = new (*this, TypeAlignment)
3369 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003370
3371 Types.push_back(TypeParm);
3372 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3373
3374 return QualType(TypeParm, 0);
3375}
3376
John McCalle78aac42010-03-10 03:28:59 +00003377TypeSourceInfo *
3378ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3379 SourceLocation NameLoc,
3380 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003381 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003382 assert(!Name.getAsDependentTemplateName() &&
3383 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003384 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003385
3386 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003387 TemplateSpecializationTypeLoc TL =
3388 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003389 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003390 TL.setTemplateNameLoc(NameLoc);
3391 TL.setLAngleLoc(Args.getLAngleLoc());
3392 TL.setRAngleLoc(Args.getRAngleLoc());
3393 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3394 TL.setArgLocInfo(i, Args[i].getLocInfo());
3395 return DI;
3396}
3397
Mike Stump11289f42009-09-09 15:08:12 +00003398QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003399ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003400 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003401 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003402 assert(!Template.getAsDependentTemplateName() &&
3403 "No dependent template names here!");
3404
John McCall6b51f282009-11-23 01:53:49 +00003405 unsigned NumArgs = Args.size();
3406
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003407 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003408 ArgVec.reserve(NumArgs);
3409 for (unsigned i = 0; i != NumArgs; ++i)
3410 ArgVec.push_back(Args[i].getArgument());
3411
John McCall2408e322010-04-27 00:57:59 +00003412 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003413 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003414}
3415
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003416#ifndef NDEBUG
3417static bool hasAnyPackExpansions(const TemplateArgument *Args,
3418 unsigned NumArgs) {
3419 for (unsigned I = 0; I != NumArgs; ++I)
3420 if (Args[I].isPackExpansion())
3421 return true;
3422
3423 return true;
3424}
3425#endif
3426
John McCall0ad16662009-10-29 08:12:44 +00003427QualType
3428ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003429 const TemplateArgument *Args,
3430 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003431 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003432 assert(!Template.getAsDependentTemplateName() &&
3433 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003434 // Look through qualified template names.
3435 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3436 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003437
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003438 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003439 Template.getAsTemplateDecl() &&
3440 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003441 QualType CanonType;
3442 if (!Underlying.isNull())
3443 CanonType = getCanonicalType(Underlying);
3444 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003445 // We can get here with an alias template when the specialization contains
3446 // a pack expansion that does not match up with a parameter pack.
3447 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3448 "Caller must compute aliased type");
3449 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003450 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3451 NumArgs);
3452 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003453
Douglas Gregora8e02e72009-07-28 23:00:59 +00003454 // Allocate the (non-canonical) template specialization type, but don't
3455 // try to unique it: these types typically have location information that
3456 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003457 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3458 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003459 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003460 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003461 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003462 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3463 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003464
Douglas Gregor8bf42052009-02-09 18:46:07 +00003465 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003466 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003467}
3468
Mike Stump11289f42009-09-09 15:08:12 +00003469QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003470ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3471 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003472 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003473 assert(!Template.getAsDependentTemplateName() &&
3474 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003475
Douglas Gregore29139c2011-03-03 17:04:51 +00003476 // Look through qualified template names.
3477 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3478 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003479
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003480 // Build the canonical template specialization type.
3481 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003482 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003483 CanonArgs.reserve(NumArgs);
3484 for (unsigned I = 0; I != NumArgs; ++I)
3485 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3486
3487 // Determine whether this canonical template specialization type already
3488 // exists.
3489 llvm::FoldingSetNodeID ID;
3490 TemplateSpecializationType::Profile(ID, CanonTemplate,
3491 CanonArgs.data(), NumArgs, *this);
3492
Craig Topper36250ad2014-05-12 05:36:57 +00003493 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003494 TemplateSpecializationType *Spec
3495 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3496
3497 if (!Spec) {
3498 // Allocate a new canonical template specialization type.
3499 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3500 sizeof(TemplateArgument) * NumArgs),
3501 TypeAlignment);
3502 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3503 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003504 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003505 Types.push_back(Spec);
3506 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3507 }
3508
3509 assert(Spec->isDependentType() &&
3510 "Non-dependent template-id type must have a canonical type");
3511 return QualType(Spec, 0);
3512}
3513
3514QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003515ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3516 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003517 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003518 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003519 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003520
Craig Topper36250ad2014-05-12 05:36:57 +00003521 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003522 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003523 if (T)
3524 return QualType(T, 0);
3525
Douglas Gregorc42075a2010-02-04 18:10:26 +00003526 QualType Canon = NamedType;
3527 if (!Canon.isCanonical()) {
3528 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003529 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3530 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003531 (void)CheckT;
3532 }
3533
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003534 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003535 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003536 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003537 return QualType(T, 0);
3538}
3539
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003540QualType
Jay Foad39c79802011-01-12 09:06:06 +00003541ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003542 llvm::FoldingSetNodeID ID;
3543 ParenType::Profile(ID, InnerType);
3544
Craig Topper36250ad2014-05-12 05:36:57 +00003545 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003546 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3547 if (T)
3548 return QualType(T, 0);
3549
3550 QualType Canon = InnerType;
3551 if (!Canon.isCanonical()) {
3552 Canon = getCanonicalType(InnerType);
3553 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3554 assert(!CheckT && "Paren canonical type broken");
3555 (void)CheckT;
3556 }
3557
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003558 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003559 Types.push_back(T);
3560 ParenTypes.InsertNode(T, InsertPos);
3561 return QualType(T, 0);
3562}
3563
Douglas Gregor02085352010-03-31 20:19:30 +00003564QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3565 NestedNameSpecifier *NNS,
3566 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003567 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003568 if (Canon.isNull()) {
3569 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003570 ElaboratedTypeKeyword CanonKeyword = Keyword;
3571 if (Keyword == ETK_None)
3572 CanonKeyword = ETK_Typename;
3573
3574 if (CanonNNS != NNS || CanonKeyword != Keyword)
3575 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003576 }
3577
3578 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003579 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003580
Craig Topper36250ad2014-05-12 05:36:57 +00003581 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003582 DependentNameType *T
3583 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003584 if (T)
3585 return QualType(T, 0);
3586
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003587 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003588 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003589 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003590 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003591}
3592
Mike Stump11289f42009-09-09 15:08:12 +00003593QualType
John McCallc392f372010-06-11 00:33:02 +00003594ASTContext::getDependentTemplateSpecializationType(
3595 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003596 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003597 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003598 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003599 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003600 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003601 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3602 ArgCopy.push_back(Args[I].getArgument());
3603 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3604 ArgCopy.size(),
3605 ArgCopy.data());
3606}
3607
3608QualType
3609ASTContext::getDependentTemplateSpecializationType(
3610 ElaboratedTypeKeyword Keyword,
3611 NestedNameSpecifier *NNS,
3612 const IdentifierInfo *Name,
3613 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003614 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003615 assert((!NNS || NNS->isDependent()) &&
3616 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003617
Douglas Gregorc42075a2010-02-04 18:10:26 +00003618 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003619 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3620 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003621
Craig Topper36250ad2014-05-12 05:36:57 +00003622 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003623 DependentTemplateSpecializationType *T
3624 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003625 if (T)
3626 return QualType(T, 0);
3627
John McCallc392f372010-06-11 00:33:02 +00003628 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003629
John McCallc392f372010-06-11 00:33:02 +00003630 ElaboratedTypeKeyword CanonKeyword = Keyword;
3631 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3632
3633 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003634 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003635 for (unsigned I = 0; I != NumArgs; ++I) {
3636 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3637 if (!CanonArgs[I].structurallyEquals(Args[I]))
3638 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003639 }
3640
John McCallc392f372010-06-11 00:33:02 +00003641 QualType Canon;
3642 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3643 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3644 Name, NumArgs,
3645 CanonArgs.data());
3646
3647 // Find the insert position again.
3648 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3649 }
3650
3651 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3652 sizeof(TemplateArgument) * NumArgs),
3653 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003654 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003655 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003656 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003657 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003658 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003659}
3660
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003661QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003662 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003663 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003664 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003665
3666 assert(Pattern->containsUnexpandedParameterPack() &&
3667 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003668 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003669 PackExpansionType *T
3670 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3671 if (T)
3672 return QualType(T, 0);
3673
3674 QualType Canon;
3675 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003676 Canon = getCanonicalType(Pattern);
3677 // The canonical type might not contain an unexpanded parameter pack, if it
3678 // contains an alias template specialization which ignores one of its
3679 // parameters.
3680 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003681 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003682
Richard Smith68eea502012-07-16 00:20:35 +00003683 // Find the insert position again, in case we inserted an element into
3684 // PackExpansionTypes and invalidated our insert position.
3685 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3686 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003687 }
3688
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003689 T = new (*this, TypeAlignment)
3690 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003691 Types.push_back(T);
3692 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003693 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003694}
3695
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003696/// CmpProtocolNames - Comparison predicate for sorting protocols
3697/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003698static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3699 ObjCProtocolDecl *const *RHS) {
3700 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003701}
3702
Craig Topper1f26d5b2016-01-03 19:43:23 +00003703static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3704 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003705
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003706 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3707 return false;
3708
Craig Topper1f26d5b2016-01-03 19:43:23 +00003709 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003710 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003711 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003712 return false;
3713 return true;
3714}
3715
Craig Topper6a8c1512015-10-22 01:56:18 +00003716static void
3717SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003718 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003719 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003720
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003721 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003722 for (ObjCProtocolDecl *&P : Protocols)
3723 P = P->getCanonicalDecl();
3724
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003725 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003726 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3727 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003728}
3729
John McCall8b07ec22010-05-15 11:32:37 +00003730QualType ASTContext::getObjCObjectType(QualType BaseType,
3731 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003732 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003733 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003734 llvm::makeArrayRef(Protocols, NumProtocols),
3735 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003736}
3737
3738QualType ASTContext::getObjCObjectType(
3739 QualType baseType,
3740 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003741 ArrayRef<ObjCProtocolDecl *> protocols,
3742 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003743 // If the base type is an interface and there aren't any protocols or
3744 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003745 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3746 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003747 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003748
3749 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003750 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003751 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003752 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003753 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3754 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003755
Douglas Gregore9d95f12015-07-07 03:57:35 +00003756 // Determine the type arguments to be used for canonicalization,
3757 // which may be explicitly specified here or written on the base
3758 // type.
3759 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3760 if (effectiveTypeArgs.empty()) {
3761 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3762 effectiveTypeArgs = baseObject->getTypeArgs();
3763 }
John McCallfc93cf92009-10-22 22:37:11 +00003764
Douglas Gregore9d95f12015-07-07 03:57:35 +00003765 // Build the canonical type, which has the canonical base type and a
3766 // sorted-and-uniqued list of protocols and the type arguments
3767 // canonicalized.
3768 QualType canonical;
3769 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3770 effectiveTypeArgs.end(),
3771 [&](QualType type) {
3772 return type.isCanonical();
3773 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00003774 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003775 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3776 // Determine the canonical type arguments.
3777 ArrayRef<QualType> canonTypeArgs;
3778 SmallVector<QualType, 4> canonTypeArgsVec;
3779 if (!typeArgsAreCanonical) {
3780 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3781 for (auto typeArg : effectiveTypeArgs)
3782 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3783 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003784 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003785 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003786 }
3787
Douglas Gregore9d95f12015-07-07 03:57:35 +00003788 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3789 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3790 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003791 canonProtocolsVec.append(protocols.begin(), protocols.end());
3792 SortAndUniqueProtocols(canonProtocolsVec);
3793 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003794 } else {
3795 canonProtocols = protocols;
3796 }
3797
3798 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003799 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003800
John McCallfc93cf92009-10-22 22:37:11 +00003801 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003802 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3803 }
3804
Douglas Gregore9d95f12015-07-07 03:57:35 +00003805 unsigned size = sizeof(ObjCObjectTypeImpl);
3806 size += typeArgs.size() * sizeof(QualType);
3807 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3808 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003809 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003810 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3811 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003812
3813 Types.push_back(T);
3814 ObjCObjectTypes.InsertNode(T, InsertPos);
3815 return QualType(T, 0);
3816}
3817
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003818/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3819/// protocol list adopt all protocols in QT's qualified-id protocol
3820/// list.
3821bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3822 ObjCInterfaceDecl *IC) {
3823 if (!QT->isObjCQualifiedIdType())
3824 return false;
3825
3826 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3827 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003828 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003829 if (!IC->ClassImplementsProtocol(Proto, false))
3830 return false;
3831 }
3832 return true;
3833 }
3834 return false;
3835}
3836
3837/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3838/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3839/// of protocols.
3840bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3841 ObjCInterfaceDecl *IDecl) {
3842 if (!QT->isObjCQualifiedIdType())
3843 return false;
3844 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3845 if (!OPT)
3846 return false;
3847 if (!IDecl->hasDefinition())
3848 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003849 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3850 CollectInheritedProtocols(IDecl, InheritedProtocols);
3851 if (InheritedProtocols.empty())
3852 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003853 // Check that if every protocol in list of id<plist> conforms to a protcol
3854 // of IDecl's, then bridge casting is ok.
3855 bool Conforms = false;
3856 for (auto *Proto : OPT->quals()) {
3857 Conforms = false;
3858 for (auto *PI : InheritedProtocols) {
3859 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3860 Conforms = true;
3861 break;
3862 }
3863 }
3864 if (!Conforms)
3865 break;
3866 }
3867 if (Conforms)
3868 return true;
3869
Aaron Ballman83731462014-03-17 16:14:00 +00003870 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003871 // If both the right and left sides have qualifiers.
3872 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003873 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003874 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003875 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003876 break;
3877 }
3878 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003879 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003880 }
3881 return true;
3882}
3883
John McCall8b07ec22010-05-15 11:32:37 +00003884/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3885/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003886QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003887 llvm::FoldingSetNodeID ID;
3888 ObjCObjectPointerType::Profile(ID, ObjectT);
3889
Craig Topper36250ad2014-05-12 05:36:57 +00003890 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003891 if (ObjCObjectPointerType *QT =
3892 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3893 return QualType(QT, 0);
3894
3895 // Find the canonical object type.
3896 QualType Canonical;
3897 if (!ObjectT.isCanonical()) {
3898 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3899
3900 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003901 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3902 }
3903
Douglas Gregorf85bee62010-02-08 22:59:26 +00003904 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003905 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3906 ObjCObjectPointerType *QType =
3907 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003908
Steve Narofffb4330f2009-06-17 22:40:22 +00003909 Types.push_back(QType);
3910 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003911 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003912}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003913
Douglas Gregor1c283312010-08-11 12:19:30 +00003914/// getObjCInterfaceType - Return the unique reference to the type for the
3915/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003916QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3917 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003918 if (Decl->TypeForDecl)
3919 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003920
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003921 if (PrevDecl) {
3922 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3923 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3924 return QualType(PrevDecl->TypeForDecl, 0);
3925 }
3926
Douglas Gregor7671e532011-12-16 16:34:57 +00003927 // Prefer the definition, if there is one.
3928 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3929 Decl = Def;
3930
Douglas Gregor1c283312010-08-11 12:19:30 +00003931 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3932 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3933 Decl->TypeForDecl = T;
3934 Types.push_back(T);
3935 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003936}
3937
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003938/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3939/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003940/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003941/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003942/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003943QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003944 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003945 if (tofExpr->isTypeDependent()) {
3946 llvm::FoldingSetNodeID ID;
3947 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003948
Craig Topper36250ad2014-05-12 05:36:57 +00003949 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003950 DependentTypeOfExprType *Canon
3951 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3952 if (Canon) {
3953 // We already have a "canonical" version of an identical, dependent
3954 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003955 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003956 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003957 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003958 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003959 Canon
3960 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003961 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3962 toe = Canon;
3963 }
3964 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003965 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003966 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003967 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003968 Types.push_back(toe);
3969 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003970}
3971
Steve Naroffa773cd52007-08-01 18:02:17 +00003972/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003973/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003974/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003975/// an issue. This doesn't affect the type checker, since it operates
3976/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003977QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003978 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003979 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003980 Types.push_back(tot);
3981 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003982}
3983
Richard Smith8eb1d322014-06-05 20:13:13 +00003984/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3985/// nodes. This would never be helpful, since each such type has its own
3986/// expression, and would not give a significant memory saving, since there
3987/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003988QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003989 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003990
3991 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003992 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003993 // unique dependent type. Two such decltype-specifiers refer to the same
3994 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003995 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003996 llvm::FoldingSetNodeID ID;
3997 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003998
Craig Topper36250ad2014-05-12 05:36:57 +00003999 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004000 DependentDecltypeType *Canon
4001 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004002 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004003 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004004 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004005 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004006 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004007 dt = new (*this, TypeAlignment)
4008 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004009 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004010 dt = new (*this, TypeAlignment)
4011 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004012 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004013 Types.push_back(dt);
4014 return QualType(dt, 0);
4015}
4016
Alexis Hunte852b102011-05-24 22:41:36 +00004017/// getUnaryTransformationType - We don't unique these, since the memory
4018/// savings are minimal and these are rare.
4019QualType ASTContext::getUnaryTransformType(QualType BaseType,
4020 QualType UnderlyingType,
4021 UnaryTransformType::UTTKind Kind)
4022 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004023 UnaryTransformType *ut = nullptr;
4024
4025 if (BaseType->isDependentType()) {
4026 // Look in the folding set for an existing type.
4027 llvm::FoldingSetNodeID ID;
4028 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4029
4030 void *InsertPos = nullptr;
4031 DependentUnaryTransformType *Canon
4032 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4033
4034 if (!Canon) {
4035 // Build a new, canonical __underlying_type(type) type.
4036 Canon = new (*this, TypeAlignment)
4037 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4038 Kind);
4039 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4040 }
4041 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4042 QualType(), Kind,
4043 QualType(Canon, 0));
4044 } else {
4045 QualType CanonType = getCanonicalType(UnderlyingType);
4046 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4047 UnderlyingType, Kind,
4048 CanonType);
4049 }
4050 Types.push_back(ut);
4051 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004052}
4053
Richard Smith2a7d4812013-05-04 07:00:32 +00004054/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4055/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4056/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004057QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004058 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004059 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004060 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004061
Richard Smith2a7d4812013-05-04 07:00:32 +00004062 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004063 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004064 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004065 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004066 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4067 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004068
Richard Smith74aeef52013-04-26 16:15:35 +00004069 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004070 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004071 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004072 Types.push_back(AT);
4073 if (InsertPos)
4074 AutoTypes.InsertNode(AT, InsertPos);
4075 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004076}
4077
Eli Friedman0dfb8892011-10-06 23:00:33 +00004078/// getAtomicType - Return the uniqued reference to the atomic type for
4079/// the given value type.
4080QualType ASTContext::getAtomicType(QualType T) const {
4081 // Unique pointers, to guarantee there is only one pointer of a particular
4082 // structure.
4083 llvm::FoldingSetNodeID ID;
4084 AtomicType::Profile(ID, T);
4085
Craig Topper36250ad2014-05-12 05:36:57 +00004086 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004087 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4088 return QualType(AT, 0);
4089
4090 // If the atomic value type isn't canonical, this won't be a canonical type
4091 // either, so fill in the canonical type field.
4092 QualType Canonical;
4093 if (!T.isCanonical()) {
4094 Canonical = getAtomicType(getCanonicalType(T));
4095
4096 // Get the new insert position for the node we care about.
4097 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004098 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004099 }
4100 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4101 Types.push_back(New);
4102 AtomicTypes.InsertNode(New, InsertPos);
4103 return QualType(New, 0);
4104}
4105
Richard Smith02e85f32011-04-14 22:09:26 +00004106/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4107QualType ASTContext::getAutoDeductType() const {
4108 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004109 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004110 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004111 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004112 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004113 return AutoDeductTy;
4114}
4115
4116/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4117QualType ASTContext::getAutoRRefDeductType() const {
4118 if (AutoRRefDeductTy.isNull())
4119 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4120 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4121 return AutoRRefDeductTy;
4122}
4123
Chris Lattnerfb072462007-01-23 05:45:31 +00004124/// getTagDeclType - Return the unique reference to the type for the
4125/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004126QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004127 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004128 // FIXME: What is the design on getTagDeclType when it requires casting
4129 // away const? mutable?
4130 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004131}
4132
Mike Stump11289f42009-09-09 15:08:12 +00004133/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4134/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4135/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004136CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004137 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004138}
Chris Lattnerfb072462007-01-23 05:45:31 +00004139
Hans Wennborg27541db2011-10-27 08:29:09 +00004140/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4141CanQualType ASTContext::getIntMaxType() const {
4142 return getFromTargetType(Target->getIntMaxType());
4143}
4144
4145/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4146CanQualType ASTContext::getUIntMaxType() const {
4147 return getFromTargetType(Target->getUIntMaxType());
4148}
4149
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004150/// getSignedWCharType - Return the type of "signed wchar_t".
4151/// Used when in C++, as a GCC extension.
4152QualType ASTContext::getSignedWCharType() const {
4153 // FIXME: derive from "Target" ?
4154 return WCharTy;
4155}
4156
4157/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4158/// Used when in C++, as a GCC extension.
4159QualType ASTContext::getUnsignedWCharType() const {
4160 // FIXME: derive from "Target" ?
4161 return UnsignedIntTy;
4162}
4163
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004164QualType ASTContext::getIntPtrType() const {
4165 return getFromTargetType(Target->getIntPtrType());
4166}
4167
4168QualType ASTContext::getUIntPtrType() const {
4169 return getCorrespondingUnsignedType(getIntPtrType());
4170}
4171
Hans Wennborg27541db2011-10-27 08:29:09 +00004172/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004173/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4174QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004175 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004176}
4177
Eli Friedman4e91899e2012-11-27 02:58:24 +00004178/// \brief Return the unique type for "pid_t" defined in
4179/// <sys/types.h>. We need this to compute the correct type for vfork().
4180QualType ASTContext::getProcessIDType() const {
4181 return getFromTargetType(Target->getProcessIDType());
4182}
4183
Chris Lattnera21ad802008-04-02 05:18:44 +00004184//===----------------------------------------------------------------------===//
4185// Type Operators
4186//===----------------------------------------------------------------------===//
4187
Jay Foad39c79802011-01-12 09:06:06 +00004188CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004189 // Push qualifiers into arrays, and then discard any remaining
4190 // qualifiers.
4191 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004192 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004193 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004194 QualType Result;
4195 if (isa<ArrayType>(Ty)) {
4196 Result = getArrayDecayedType(QualType(Ty,0));
4197 } else if (isa<FunctionType>(Ty)) {
4198 Result = getPointerType(QualType(Ty, 0));
4199 } else {
4200 Result = QualType(Ty, 0);
4201 }
4202
4203 return CanQualType::CreateUnsafe(Result);
4204}
4205
John McCall6c9dd522011-01-18 07:41:22 +00004206QualType ASTContext::getUnqualifiedArrayType(QualType type,
4207 Qualifiers &quals) {
4208 SplitQualType splitType = type.getSplitUnqualifiedType();
4209
4210 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4211 // the unqualified desugared type and then drops it on the floor.
4212 // We then have to strip that sugar back off with
4213 // getUnqualifiedDesugaredType(), which is silly.
4214 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004215 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004216
4217 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004218 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004219 quals = splitType.Quals;
4220 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004221 }
4222
John McCall6c9dd522011-01-18 07:41:22 +00004223 // Otherwise, recurse on the array's element type.
4224 QualType elementType = AT->getElementType();
4225 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4226
4227 // If that didn't change the element type, AT has no qualifiers, so we
4228 // can just use the results in splitType.
4229 if (elementType == unqualElementType) {
4230 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004231 quals = splitType.Quals;
4232 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004233 }
4234
4235 // Otherwise, add in the qualifiers from the outermost type, then
4236 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004237 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004238
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004239 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004240 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004241 CAT->getSizeModifier(), 0);
4242 }
4243
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004244 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004245 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004246 }
4247
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004248 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004249 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004250 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004251 VAT->getSizeModifier(),
4252 VAT->getIndexTypeCVRQualifiers(),
4253 VAT->getBracketsRange());
4254 }
4255
4256 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004257 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004258 DSAT->getSizeModifier(), 0,
4259 SourceRange());
4260}
4261
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004262/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4263/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4264/// they point to and return true. If T1 and T2 aren't pointer types
4265/// or pointer-to-member types, or if they are not similar at this
4266/// level, returns false and leaves T1 and T2 unchanged. Top-level
4267/// qualifiers on T1 and T2 are ignored. This function will typically
4268/// be called in a loop that successively "unwraps" pointer and
4269/// pointer-to-member types to compare them at each level.
4270bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4271 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4272 *T2PtrType = T2->getAs<PointerType>();
4273 if (T1PtrType && T2PtrType) {
4274 T1 = T1PtrType->getPointeeType();
4275 T2 = T2PtrType->getPointeeType();
4276 return true;
4277 }
4278
4279 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4280 *T2MPType = T2->getAs<MemberPointerType>();
4281 if (T1MPType && T2MPType &&
4282 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4283 QualType(T2MPType->getClass(), 0))) {
4284 T1 = T1MPType->getPointeeType();
4285 T2 = T2MPType->getPointeeType();
4286 return true;
4287 }
4288
David Blaikiebbafb8a2012-03-11 07:00:24 +00004289 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004290 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4291 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4292 if (T1OPType && T2OPType) {
4293 T1 = T1OPType->getPointeeType();
4294 T2 = T2OPType->getPointeeType();
4295 return true;
4296 }
4297 }
4298
4299 // FIXME: Block pointers, too?
4300
4301 return false;
4302}
4303
Jay Foad39c79802011-01-12 09:06:06 +00004304DeclarationNameInfo
4305ASTContext::getNameForTemplate(TemplateName Name,
4306 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004307 switch (Name.getKind()) {
4308 case TemplateName::QualifiedTemplate:
4309 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004310 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004311 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4312 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004313
John McCalld9dfe3a2011-06-30 08:33:18 +00004314 case TemplateName::OverloadedTemplate: {
4315 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4316 // DNInfo work in progress: CHECKME: what about DNLoc?
4317 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4318 }
4319
4320 case TemplateName::DependentTemplate: {
4321 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004322 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004323 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004324 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4325 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004326 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004327 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4328 // DNInfo work in progress: FIXME: source locations?
4329 DeclarationNameLoc DNLoc;
4330 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4331 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4332 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004333 }
4334 }
4335
John McCalld9dfe3a2011-06-30 08:33:18 +00004336 case TemplateName::SubstTemplateTemplateParm: {
4337 SubstTemplateTemplateParmStorage *subst
4338 = Name.getAsSubstTemplateTemplateParm();
4339 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4340 NameLoc);
4341 }
4342
4343 case TemplateName::SubstTemplateTemplateParmPack: {
4344 SubstTemplateTemplateParmPackStorage *subst
4345 = Name.getAsSubstTemplateTemplateParmPack();
4346 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4347 NameLoc);
4348 }
4349 }
4350
4351 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004352}
4353
Jay Foad39c79802011-01-12 09:06:06 +00004354TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004355 switch (Name.getKind()) {
4356 case TemplateName::QualifiedTemplate:
4357 case TemplateName::Template: {
4358 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004359 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004360 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004361 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4362
4363 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004364 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004365 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004366
John McCalld9dfe3a2011-06-30 08:33:18 +00004367 case TemplateName::OverloadedTemplate:
4368 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004369
John McCalld9dfe3a2011-06-30 08:33:18 +00004370 case TemplateName::DependentTemplate: {
4371 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4372 assert(DTN && "Non-dependent template names must refer to template decls.");
4373 return DTN->CanonicalTemplateName;
4374 }
4375
4376 case TemplateName::SubstTemplateTemplateParm: {
4377 SubstTemplateTemplateParmStorage *subst
4378 = Name.getAsSubstTemplateTemplateParm();
4379 return getCanonicalTemplateName(subst->getReplacement());
4380 }
4381
4382 case TemplateName::SubstTemplateTemplateParmPack: {
4383 SubstTemplateTemplateParmPackStorage *subst
4384 = Name.getAsSubstTemplateTemplateParmPack();
4385 TemplateTemplateParmDecl *canonParameter
4386 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4387 TemplateArgument canonArgPack
4388 = getCanonicalTemplateArgument(subst->getArgumentPack());
4389 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4390 }
4391 }
4392
4393 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004394}
4395
Douglas Gregoradee3e32009-11-11 23:06:43 +00004396bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4397 X = getCanonicalTemplateName(X);
4398 Y = getCanonicalTemplateName(Y);
4399 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4400}
4401
Mike Stump11289f42009-09-09 15:08:12 +00004402TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004403ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004404 switch (Arg.getKind()) {
4405 case TemplateArgument::Null:
4406 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004407
Douglas Gregora8e02e72009-07-28 23:00:59 +00004408 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004409 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004410
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004411 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004412 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004413 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004414 }
Mike Stump11289f42009-09-09 15:08:12 +00004415
Eli Friedmanb826a002012-09-26 02:36:12 +00004416 case TemplateArgument::NullPtr:
4417 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4418 /*isNullPtr*/true);
4419
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004420 case TemplateArgument::Template:
4421 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004422
4423 case TemplateArgument::TemplateExpansion:
4424 return TemplateArgument(getCanonicalTemplateName(
4425 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004426 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004427
Douglas Gregora8e02e72009-07-28 23:00:59 +00004428 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004429 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004430
Douglas Gregora8e02e72009-07-28 23:00:59 +00004431 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004432 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004433
Douglas Gregora8e02e72009-07-28 23:00:59 +00004434 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004435 if (Arg.pack_size() == 0)
4436 return Arg;
4437
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004438 TemplateArgument *CanonArgs
4439 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004440 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004441 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004442 AEnd = Arg.pack_end();
4443 A != AEnd; (void)++A, ++Idx)
4444 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004445
Benjamin Kramercce63472015-08-05 09:40:22 +00004446 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004447 }
4448 }
4449
4450 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004451 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004452}
4453
Douglas Gregor333489b2009-03-27 23:10:48 +00004454NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004455ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004456 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004457 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004458
4459 switch (NNS->getKind()) {
4460 case NestedNameSpecifier::Identifier:
4461 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004462 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004463 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4464 NNS->getAsIdentifier());
4465
4466 case NestedNameSpecifier::Namespace:
4467 // A namespace is canonical; build a nested-name-specifier with
4468 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004469 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004470 NNS->getAsNamespace()->getOriginalNamespace());
4471
4472 case NestedNameSpecifier::NamespaceAlias:
4473 // A namespace is canonical; build a nested-name-specifier with
4474 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004475 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004476 NNS->getAsNamespaceAlias()->getNamespace()
4477 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004478
4479 case NestedNameSpecifier::TypeSpec:
4480 case NestedNameSpecifier::TypeSpecWithTemplate: {
4481 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004482
4483 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4484 // break it apart into its prefix and identifier, then reconsititute those
4485 // as the canonical nested-name-specifier. This is required to canonicalize
4486 // a dependent nested-name-specifier involving typedefs of dependent-name
4487 // types, e.g.,
4488 // typedef typename T::type T1;
4489 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004490 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4491 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004492 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004493
Eli Friedman5358a0a2012-03-03 04:09:56 +00004494 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4495 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4496 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004497 return NestedNameSpecifier::Create(*this, nullptr, false,
4498 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004499 }
4500
4501 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004502 case NestedNameSpecifier::Super:
4503 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004504 return NNS;
4505 }
4506
David Blaikie8a40f702012-01-17 06:56:22 +00004507 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004508}
4509
Jay Foad39c79802011-01-12 09:06:06 +00004510const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004511 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004512 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004513 // Handle the common positive case fast.
4514 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4515 return AT;
4516 }
Mike Stump11289f42009-09-09 15:08:12 +00004517
John McCall8ccfcb52009-09-24 19:53:00 +00004518 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004519 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004520 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004521
John McCall8ccfcb52009-09-24 19:53:00 +00004522 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004523 // implements C99 6.7.3p8: "If the specification of an array type includes
4524 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004525
Chris Lattner7adf0762008-08-04 07:31:14 +00004526 // If we get here, we either have type qualifiers on the type, or we have
4527 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004528 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004529
John McCall33ddac02011-01-19 10:06:00 +00004530 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004531 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004532
Chris Lattner7adf0762008-08-04 07:31:14 +00004533 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004534 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004535 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004536 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004537
Chris Lattner7adf0762008-08-04 07:31:14 +00004538 // Otherwise, we have an array and we have qualifiers on it. Push the
4539 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004540 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004541
Chris Lattner7adf0762008-08-04 07:31:14 +00004542 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4543 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4544 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004545 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004546 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4547 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4548 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004549 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004550
Mike Stump11289f42009-09-09 15:08:12 +00004551 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004552 = dyn_cast<DependentSizedArrayType>(ATy))
4553 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004554 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004555 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004556 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004557 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004558 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004559
Chris Lattner7adf0762008-08-04 07:31:14 +00004560 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004561 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004562 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004563 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004564 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004565 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004566}
4567
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004568QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004569 if (T->isArrayType() || T->isFunctionType())
4570 return getDecayedType(T);
4571 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004572}
4573
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004574QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004575 T = getVariableArrayDecayedType(T);
4576 T = getAdjustedParameterType(T);
4577 return T.getUnqualifiedType();
4578}
4579
David Majnemerd09a51c2015-03-03 01:50:05 +00004580QualType ASTContext::getExceptionObjectType(QualType T) const {
4581 // C++ [except.throw]p3:
4582 // A throw-expression initializes a temporary object, called the exception
4583 // object, the type of which is determined by removing any top-level
4584 // cv-qualifiers from the static type of the operand of throw and adjusting
4585 // the type from "array of T" or "function returning T" to "pointer to T"
4586 // or "pointer to function returning T", [...]
4587 T = getVariableArrayDecayedType(T);
4588 if (T->isArrayType() || T->isFunctionType())
4589 T = getDecayedType(T);
4590 return T.getUnqualifiedType();
4591}
4592
Chris Lattnera21ad802008-04-02 05:18:44 +00004593/// getArrayDecayedType - Return the properly qualified result of decaying the
4594/// specified array type to a pointer. This operation is non-trivial when
4595/// handling typedefs etc. The canonical type of "T" must be an array type,
4596/// this returns a pointer to a properly qualified element of the array.
4597///
4598/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004599QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004600 // Get the element type with 'getAsArrayType' so that we don't lose any
4601 // typedefs in the element type of the array. This also handles propagation
4602 // of type qualifiers from the array type into the element type if present
4603 // (C99 6.7.3p8).
4604 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4605 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004606
Chris Lattner7adf0762008-08-04 07:31:14 +00004607 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004608
4609 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004610 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004611}
4612
John McCall33ddac02011-01-19 10:06:00 +00004613QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4614 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004615}
4616
John McCall33ddac02011-01-19 10:06:00 +00004617QualType ASTContext::getBaseElementType(QualType type) const {
4618 Qualifiers qs;
4619 while (true) {
4620 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004621 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004622 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004623
John McCall33ddac02011-01-19 10:06:00 +00004624 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004625 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004626 }
Mike Stump11289f42009-09-09 15:08:12 +00004627
John McCall33ddac02011-01-19 10:06:00 +00004628 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004629}
4630
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004631/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004632uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004633ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4634 uint64_t ElementCount = 1;
4635 do {
4636 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004637 CA = dyn_cast_or_null<ConstantArrayType>(
4638 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004639 } while (CA);
4640 return ElementCount;
4641}
4642
Steve Naroff0af91202007-04-27 21:51:21 +00004643/// getFloatingRank - Return a relative rank for floating point types.
4644/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004645static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004646 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004647 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004648
John McCall9dd450b2009-09-21 23:43:11 +00004649 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4650 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004651 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004652 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004653 case BuiltinType::Float: return FloatRank;
4654 case BuiltinType::Double: return DoubleRank;
4655 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004656 }
4657}
4658
Mike Stump11289f42009-09-09 15:08:12 +00004659/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4660/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004661/// 'typeDomain' is a real floating point or complex type.
4662/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004663QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4664 QualType Domain) const {
4665 FloatingRank EltRank = getFloatingRank(Size);
4666 if (Domain->isComplexType()) {
4667 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004668 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004669 case FloatRank: return FloatComplexTy;
4670 case DoubleRank: return DoubleComplexTy;
4671 case LongDoubleRank: return LongDoubleComplexTy;
4672 }
Steve Naroff0af91202007-04-27 21:51:21 +00004673 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004674
4675 assert(Domain->isRealFloatingType() && "Unknown domain!");
4676 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004677 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004678 case FloatRank: return FloatTy;
4679 case DoubleRank: return DoubleTy;
4680 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004681 }
David Blaikief47fa302012-01-17 02:30:50 +00004682 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004683}
4684
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004685/// getFloatingTypeOrder - Compare the rank of the two specified floating
4686/// point types, ignoring the domain of the type (i.e. 'double' ==
4687/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004688/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004689int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004690 FloatingRank LHSR = getFloatingRank(LHS);
4691 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004692
Chris Lattnerb90739d2008-04-06 23:38:49 +00004693 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004694 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004695 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004696 return 1;
4697 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004698}
4699
Chris Lattner76a00cf2008-04-06 22:59:24 +00004700/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4701/// routine will assert if passed a built-in type that isn't an integer or enum,
4702/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004703unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004704 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004705
Chris Lattner76a00cf2008-04-06 22:59:24 +00004706 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004707 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004708 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004709 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004710 case BuiltinType::Char_S:
4711 case BuiltinType::Char_U:
4712 case BuiltinType::SChar:
4713 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004714 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004715 case BuiltinType::Short:
4716 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004717 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004718 case BuiltinType::Int:
4719 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004720 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004721 case BuiltinType::Long:
4722 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004723 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004724 case BuiltinType::LongLong:
4725 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004726 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004727 case BuiltinType::Int128:
4728 case BuiltinType::UInt128:
4729 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004730 }
4731}
4732
Eli Friedman629ffb92009-08-20 04:21:42 +00004733/// \brief Whether this is a promotable bitfield reference according
4734/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4735///
4736/// \returns the type this bit-field will promote to, or NULL if no
4737/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004738QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004739 if (E->isTypeDependent() || E->isValueDependent())
4740 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004741
4742 // FIXME: We should not do this unless E->refersToBitField() is true. This
4743 // matters in C where getSourceBitField() will find bit-fields for various
4744 // cases where the source expression is not a bit-field designator.
4745
John McCalld25db7e2013-05-06 21:39:12 +00004746 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004747 if (!Field)
4748 return QualType();
4749
4750 QualType FT = Field->getType();
4751
Richard Smithcaf33902011-10-10 18:28:20 +00004752 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004753 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004754 // C++ [conv.prom]p5:
4755 // A prvalue for an integral bit-field can be converted to a prvalue of type
4756 // int if int can represent all the values of the bit-field; otherwise, it
4757 // can be converted to unsigned int if unsigned int can represent all the
4758 // values of the bit-field. If the bit-field is larger yet, no integral
4759 // promotion applies to it.
4760 // C11 6.3.1.1/2:
4761 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4762 // If an int can represent all values of the original type (as restricted by
4763 // the width, for a bit-field), the value is converted to an int; otherwise,
4764 // it is converted to an unsigned int.
4765 //
4766 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4767 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004768 if (BitWidth < IntSize)
4769 return IntTy;
4770
4771 if (BitWidth == IntSize)
4772 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4773
4774 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004775 // like the base type. GCC has some weird bugs in this area that we
4776 // deliberately do not follow (GCC follows a pre-standard resolution to
4777 // C's DR315 which treats bit-width as being part of the type, and this leaks
4778 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004779 return QualType();
4780}
4781
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004782/// getPromotedIntegerType - Returns the type that Promotable will
4783/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4784/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004785QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004786 assert(!Promotable.isNull());
4787 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004788 if (const EnumType *ET = Promotable->getAs<EnumType>())
4789 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004790
4791 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4792 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4793 // (3.9.1) can be converted to a prvalue of the first of the following
4794 // types that can represent all the values of its underlying type:
4795 // int, unsigned int, long int, unsigned long int, long long int, or
4796 // unsigned long long int [...]
4797 // FIXME: Is there some better way to compute this?
4798 if (BT->getKind() == BuiltinType::WChar_S ||
4799 BT->getKind() == BuiltinType::WChar_U ||
4800 BT->getKind() == BuiltinType::Char16 ||
4801 BT->getKind() == BuiltinType::Char32) {
4802 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4803 uint64_t FromSize = getTypeSize(BT);
4804 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4805 LongLongTy, UnsignedLongLongTy };
4806 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4807 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4808 if (FromSize < ToSize ||
4809 (FromSize == ToSize &&
4810 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4811 return PromoteTypes[Idx];
4812 }
4813 llvm_unreachable("char type should fit into long long");
4814 }
4815 }
4816
4817 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004818 if (Promotable->isSignedIntegerType())
4819 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004820 uint64_t PromotableSize = getIntWidth(Promotable);
4821 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004822 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4823 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4824}
4825
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004826/// \brief Recurses in pointer/array types until it finds an objc retainable
4827/// type and returns its ownership.
4828Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4829 while (!T.isNull()) {
4830 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4831 return T.getObjCLifetime();
4832 if (T->isArrayType())
4833 T = getBaseElementType(T);
4834 else if (const PointerType *PT = T->getAs<PointerType>())
4835 T = PT->getPointeeType();
4836 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004837 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004838 else
4839 break;
4840 }
4841
4842 return Qualifiers::OCL_None;
4843}
4844
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004845static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4846 // Incomplete enum types are not treated as integer types.
4847 // FIXME: In C++, enum types are never integer types.
4848 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4849 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004850 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004851}
4852
Mike Stump11289f42009-09-09 15:08:12 +00004853/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004854/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004855/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004856int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004857 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4858 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004859
4860 // Unwrap enums to their underlying type.
4861 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4862 LHSC = getIntegerTypeForEnum(ET);
4863 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4864 RHSC = getIntegerTypeForEnum(ET);
4865
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004866 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004867
Chris Lattner76a00cf2008-04-06 22:59:24 +00004868 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4869 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004870
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004871 unsigned LHSRank = getIntegerRank(LHSC);
4872 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004873
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004874 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4875 if (LHSRank == RHSRank) return 0;
4876 return LHSRank > RHSRank ? 1 : -1;
4877 }
Mike Stump11289f42009-09-09 15:08:12 +00004878
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004879 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4880 if (LHSUnsigned) {
4881 // If the unsigned [LHS] type is larger, return it.
4882 if (LHSRank >= RHSRank)
4883 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004884
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004885 // If the signed type can represent all values of the unsigned type, it
4886 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004887 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004888 return -1;
4889 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004890
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004891 // If the unsigned [RHS] type is larger, return it.
4892 if (RHSRank >= LHSRank)
4893 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004894
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004895 // If the signed type can represent all values of the unsigned type, it
4896 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004897 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004898 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004899}
Anders Carlsson98f07902007-08-17 05:31:46 +00004900
Ben Langmuirf5416742016-02-04 00:55:24 +00004901TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004902 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004903 assert(!CFConstantStringTagDecl &&
4904 "tag and typedef should be initialized together");
4905 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
4906 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004907
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004908 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00004909 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00004910
Anders Carlsson98f07902007-08-17 05:31:46 +00004911 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004912 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004913 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004914 // int flags;
4915 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004916 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00004917 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004918 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004919 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00004920 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004921 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004922 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00004923
Anders Carlsson98f07902007-08-17 05:31:46 +00004924 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004925 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004926 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004927 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00004928 SourceLocation(),
4929 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00004930 FieldTypes[i], /*TInfo=*/nullptr,
4931 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004932 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004933 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004934 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00004935 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004936 }
4937
Ben Langmuirf5416742016-02-04 00:55:24 +00004938 CFConstantStringTagDecl->completeDefinition();
4939 // This type is designed to be compatible with NSConstantString, but cannot
4940 // use the same name, since NSConstantString is an interface.
4941 auto tagType = getTagDeclType(CFConstantStringTagDecl);
4942 CFConstantStringTypeDecl =
4943 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00004944 }
Mike Stump11289f42009-09-09 15:08:12 +00004945
Quentin Colombet043406b2016-02-03 22:41:00 +00004946 return CFConstantStringTypeDecl;
4947}
4948
Ben Langmuirf5416742016-02-04 00:55:24 +00004949RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
4950 if (!CFConstantStringTagDecl)
4951 getCFConstantStringDecl(); // Build the tag and the typedef.
4952 return CFConstantStringTagDecl;
4953}
4954
Quentin Colombet043406b2016-02-03 22:41:00 +00004955// getCFConstantStringType - Return the type used for constant CFStrings.
4956QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00004957 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00004958}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004959
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004960QualType ASTContext::getObjCSuperType() const {
4961 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004962 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004963 TUDecl->addDecl(ObjCSuperTypeDecl);
4964 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4965 }
4966 return ObjCSuperType;
4967}
4968
Douglas Gregor512b0772009-04-23 22:29:11 +00004969void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004970 const TypedefType *TD = T->getAs<TypedefType>();
4971 assert(TD && "Invalid CFConstantStringType");
4972 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
4973 auto TagType =
4974 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
4975 assert(TagType && "Invalid CFConstantStringType");
4976 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00004977}
4978
Jay Foad39c79802011-01-12 09:06:06 +00004979QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004980 if (BlockDescriptorType)
4981 return getTagDeclType(BlockDescriptorType);
4982
Alp Toker2dea15b2013-12-17 01:22:38 +00004983 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004984 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004985 RD = buildImplicitRecord("__block_descriptor");
4986 RD->startDefinition();
4987
Mike Stumpd0153282009-10-20 02:12:22 +00004988 QualType FieldTypes[] = {
4989 UnsignedLongTy,
4990 UnsignedLongTy,
4991 };
4992
Craig Topperd6d31ac2013-07-15 08:24:27 +00004993 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004994 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004995 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004996 };
4997
4998 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004999 FieldDecl *Field = FieldDecl::Create(
5000 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005001 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5002 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005003 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005004 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005005 }
5006
Alp Toker2dea15b2013-12-17 01:22:38 +00005007 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005008
Alp Toker2dea15b2013-12-17 01:22:38 +00005009 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005010
5011 return getTagDeclType(BlockDescriptorType);
5012}
5013
Jay Foad39c79802011-01-12 09:06:06 +00005014QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005015 if (BlockDescriptorExtendedType)
5016 return getTagDeclType(BlockDescriptorExtendedType);
5017
Alp Toker2dea15b2013-12-17 01:22:38 +00005018 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005019 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005020 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5021 RD->startDefinition();
5022
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005023 QualType FieldTypes[] = {
5024 UnsignedLongTy,
5025 UnsignedLongTy,
5026 getPointerType(VoidPtrTy),
5027 getPointerType(VoidPtrTy)
5028 };
5029
Craig Topperd6d31ac2013-07-15 08:24:27 +00005030 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005031 "reserved",
5032 "Size",
5033 "CopyFuncPtr",
5034 "DestroyFuncPtr"
5035 };
5036
5037 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005038 FieldDecl *Field = FieldDecl::Create(
5039 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005040 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5041 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005042 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005043 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005044 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005045 }
5046
Alp Toker2dea15b2013-12-17 01:22:38 +00005047 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005048
Alp Toker2dea15b2013-12-17 01:22:38 +00005049 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005050 return getTagDeclType(BlockDescriptorExtendedType);
5051}
5052
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005053/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5054/// requires copy/dispose. Note that this must match the logic
5055/// in buildByrefHelpers.
5056bool ASTContext::BlockRequiresCopying(QualType Ty,
5057 const VarDecl *D) {
5058 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5059 const Expr *copyExpr = getBlockVarCopyInits(D);
5060 if (!copyExpr && record->hasTrivialDestructor()) return false;
5061
Mike Stump94967902009-10-21 18:16:27 +00005062 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005063 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005064
5065 if (!Ty->isObjCRetainableType()) return false;
5066
5067 Qualifiers qs = Ty.getQualifiers();
5068
5069 // If we have lifetime, that dominates.
5070 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005071 switch (lifetime) {
5072 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5073
5074 // These are just bits as far as the runtime is concerned.
5075 case Qualifiers::OCL_ExplicitNone:
5076 case Qualifiers::OCL_Autoreleasing:
5077 return false;
5078
5079 // Tell the runtime that this is ARC __weak, called by the
5080 // byref routines.
5081 case Qualifiers::OCL_Weak:
5082 // ARC __strong __block variables need to be retained.
5083 case Qualifiers::OCL_Strong:
5084 return true;
5085 }
5086 llvm_unreachable("fell out of lifetime switch!");
5087 }
5088 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5089 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005090}
5091
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005092bool ASTContext::getByrefLifetime(QualType Ty,
5093 Qualifiers::ObjCLifetime &LifeTime,
5094 bool &HasByrefExtendedLayout) const {
5095
5096 if (!getLangOpts().ObjC1 ||
5097 getLangOpts().getGC() != LangOptions::NonGC)
5098 return false;
5099
5100 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005101 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005102 HasByrefExtendedLayout = true;
5103 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005104 } else if ((LifeTime = Ty.getObjCLifetime())) {
5105 // Honor the ARC qualifiers.
5106 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5107 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005108 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005109 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005110 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005111 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005112 return true;
5113}
5114
Douglas Gregorbab8a962011-09-08 01:46:34 +00005115TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5116 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005117 ObjCInstanceTypeDecl =
5118 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005119 return ObjCInstanceTypeDecl;
5120}
5121
Anders Carlsson18acd442007-10-29 06:33:42 +00005122// This returns true if a type has been typedefed to BOOL:
5123// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005124static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005125 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005126 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5127 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005128
Anders Carlssond8499822007-10-29 05:01:08 +00005129 return false;
5130}
5131
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005132/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005133/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005134CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005135 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5136 return CharUnits::Zero();
5137
Ken Dyck40775002010-01-11 17:06:35 +00005138 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005139
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005140 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005141 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005142 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005143 // Treat arrays as pointers, since that's how they're passed in.
5144 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005145 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005146 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005147}
5148
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005149bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005150 return getTargetInfo().getCXXABI().isMicrosoft() &&
5151 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005152 VD->getType()->isIntegralOrEnumerationType() &&
5153 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005154}
5155
Ken Dyck40775002010-01-11 17:06:35 +00005156static inline
5157std::string charUnitsToString(const CharUnits &CU) {
5158 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005159}
5160
John McCall351762c2011-02-07 10:33:21 +00005161/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005162/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005163std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5164 std::string S;
5165
David Chisnall950a9512009-11-17 19:33:30 +00005166 const BlockDecl *Decl = Expr->getBlockDecl();
5167 QualType BlockTy =
5168 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5169 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005170 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005171 getObjCEncodingForMethodParameter(
5172 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5173 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005174 else
Alp Toker314cc812014-01-25 16:55:45 +00005175 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005176 // Compute size of all parameters.
5177 // Start with computing size of a pointer in number of bytes.
5178 // FIXME: There might(should) be a better way of doing this computation!
5179 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005180 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5181 CharUnits ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005182 for (auto PI : Decl->params()) {
5183 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005184 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005185 if (sz.isZero())
5186 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005187 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005188 ParmOffset += sz;
5189 }
5190 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005191 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005192 // Block pointer and offset.
5193 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005194
5195 // Argument types.
5196 ParmOffset = PtrSize;
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005197 for (auto PVDecl : Decl->params()) {
David Chisnall950a9512009-11-17 19:33:30 +00005198 QualType PType = PVDecl->getOriginalType();
5199 if (const ArrayType *AT =
5200 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5201 // Use array's original type only if it has known number of
5202 // elements.
5203 if (!isa<ConstantArrayType>(AT))
5204 PType = PVDecl->getType();
5205 } else if (PType->isFunctionType())
5206 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005207 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005208 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5209 S, true /*Extended*/);
5210 else
5211 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005212 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005213 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005214 }
John McCall351762c2011-02-07 10:33:21 +00005215
5216 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005217}
5218
Douglas Gregora9d84932011-05-27 01:19:52 +00005219bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005220 std::string& S) {
5221 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005222 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005223 CharUnits ParmOffset;
5224 // Compute size of all parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005225 for (auto PI : Decl->params()) {
5226 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005227 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005228 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005229 continue;
5230
David Chisnall50e4eba2010-12-30 14:05:53 +00005231 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005232 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005233 ParmOffset += sz;
5234 }
5235 S += charUnitsToString(ParmOffset);
5236 ParmOffset = CharUnits::Zero();
5237
5238 // Argument types.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005239 for (auto PVDecl : Decl->params()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005240 QualType PType = PVDecl->getOriginalType();
5241 if (const ArrayType *AT =
5242 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5243 // Use array's original type only if it has known number of
5244 // elements.
5245 if (!isa<ConstantArrayType>(AT))
5246 PType = PVDecl->getType();
5247 } else if (PType->isFunctionType())
5248 PType = PVDecl->getType();
5249 getObjCEncodingForType(PType, S);
5250 S += charUnitsToString(ParmOffset);
5251 ParmOffset += getObjCEncodingTypeSize(PType);
5252 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005253
5254 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005255}
5256
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005257/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5258/// method parameter or return type. If Extended, include class names and
5259/// block object types.
5260void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5261 QualType T, std::string& S,
5262 bool Extended) const {
5263 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5264 getObjCEncodingForTypeQualifier(QT, S);
5265 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005266 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005267 true /*OutermostType*/,
5268 false /*EncodingProperty*/,
5269 false /*StructField*/,
5270 Extended /*EncodeBlockParameters*/,
5271 Extended /*EncodeClassNames*/);
5272}
5273
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005274/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005275/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005276bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005277 std::string& S,
5278 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005279 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005280 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005281 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5282 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005283 // Compute size of all parameters.
5284 // Start with computing size of a pointer in number of bytes.
5285 // FIXME: There might(should) be a better way of doing this computation!
5286 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005287 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005288 // The first two arguments (self and _cmd) are pointers; account for
5289 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005290 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005291 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005292 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005293 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005294 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005295 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005296 continue;
5297
Ken Dyck40775002010-01-11 17:06:35 +00005298 assert (sz.isPositive() &&
5299 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005300 ParmOffset += sz;
5301 }
Ken Dyck40775002010-01-11 17:06:35 +00005302 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005303 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005304 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005305
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005306 // Argument types.
5307 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005308 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005309 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005310 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005311 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005312 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005313 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5314 // Use array's original type only if it has known number of
5315 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005316 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005317 PType = PVDecl->getType();
5318 } else if (PType->isFunctionType())
5319 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005320 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5321 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005322 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005323 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005324 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005325
5326 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005327}
5328
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005329ObjCPropertyImplDecl *
5330ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5331 const ObjCPropertyDecl *PD,
5332 const Decl *Container) const {
5333 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005334 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005335 if (const ObjCCategoryImplDecl *CID =
5336 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005337 for (auto *PID : CID->property_impls())
5338 if (PID->getPropertyDecl() == PD)
5339 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005340 } else {
5341 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5342 for (auto *PID : OID->property_impls())
5343 if (PID->getPropertyDecl() == PD)
5344 return PID;
5345 }
5346 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005347}
5348
Daniel Dunbar4932b362008-08-28 04:38:10 +00005349/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005350/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005351/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5352/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005353/// Property attributes are stored as a comma-delimited C string. The simple
5354/// attributes readonly and bycopy are encoded as single characters. The
5355/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5356/// encoded as single characters, followed by an identifier. Property types
5357/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005358/// these attributes are defined by the following enumeration:
5359/// @code
5360/// enum PropertyAttributes {
5361/// kPropertyReadOnly = 'R', // property is read-only.
5362/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5363/// kPropertyByref = '&', // property is a reference to the value last assigned
5364/// kPropertyDynamic = 'D', // property is dynamic
5365/// kPropertyGetter = 'G', // followed by getter selector name
5366/// kPropertySetter = 'S', // followed by setter selector name
5367/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005368/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005369/// kPropertyWeak = 'W' // 'weak' property
5370/// kPropertyStrong = 'P' // property GC'able
5371/// kPropertyNonAtomic = 'N' // property non-atomic
5372/// };
5373/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005374void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005375 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005376 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005377 // Collect information from the property implementation decl(s).
5378 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005379 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005380
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005381 if (ObjCPropertyImplDecl *PropertyImpDecl =
5382 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5383 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5384 Dynamic = true;
5385 else
5386 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005387 }
5388
5389 // FIXME: This is not very efficient.
5390 S = "T";
5391
5392 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005393 // GCC has some special rules regarding encoding of properties which
5394 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005395 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005396
5397 if (PD->isReadOnly()) {
5398 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005399 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5400 S += ",C";
5401 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5402 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005403 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5404 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005405 } else {
5406 switch (PD->getSetterKind()) {
5407 case ObjCPropertyDecl::Assign: break;
5408 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005409 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005410 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005411 }
5412 }
5413
5414 // It really isn't clear at all what this means, since properties
5415 // are "dynamic by default".
5416 if (Dynamic)
5417 S += ",D";
5418
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005419 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5420 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005421
Daniel Dunbar4932b362008-08-28 04:38:10 +00005422 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5423 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005424 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005425 }
5426
5427 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5428 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005429 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005430 }
5431
5432 if (SynthesizePID) {
5433 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5434 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005435 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005436 }
5437
5438 // FIXME: OBJCGC: weak & strong
5439}
5440
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005441/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005442/// Another legacy compatibility encoding: 32-bit longs are encoded as
5443/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005444/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5445///
5446void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005447 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005448 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005449 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005450 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005451 else
Jay Foad39c79802011-01-12 09:06:06 +00005452 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005453 PointeeTy = IntTy;
5454 }
5455 }
5456}
5457
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005458void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005459 const FieldDecl *Field,
5460 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005461 // We follow the behavior of gcc, expanding structures which are
5462 // directly pointed to, and expanding embedded structures. Note that
5463 // these rules are sufficient to prevent recursive encoding of the
5464 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005465 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005466 true /* outermost type */, false, false,
5467 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005468}
5469
Joe Groff98ac7d22014-07-07 22:25:15 +00005470void ASTContext::getObjCEncodingForPropertyType(QualType T,
5471 std::string& S) const {
5472 // Encode result type.
5473 // GCC has some special rules regarding encoding of properties which
5474 // closely resembles encoding of ivars.
5475 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5476 true /* outermost type */,
5477 true /* encoding property */);
5478}
5479
John McCall393a78d2012-12-20 02:45:14 +00005480static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5481 BuiltinType::Kind kind) {
5482 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005483 case BuiltinType::Void: return 'v';
5484 case BuiltinType::Bool: return 'B';
5485 case BuiltinType::Char_U:
5486 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005487 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005488 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005489 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005490 case BuiltinType::UInt: return 'I';
5491 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005492 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005493 case BuiltinType::UInt128: return 'T';
5494 case BuiltinType::ULongLong: return 'Q';
5495 case BuiltinType::Char_S:
5496 case BuiltinType::SChar: return 'c';
5497 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005498 case BuiltinType::WChar_S:
5499 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005500 case BuiltinType::Int: return 'i';
5501 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005502 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005503 case BuiltinType::LongLong: return 'q';
5504 case BuiltinType::Int128: return 't';
5505 case BuiltinType::Float: return 'f';
5506 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005507 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005508 case BuiltinType::NullPtr: return '*'; // like char*
5509
5510 case BuiltinType::Half:
5511 // FIXME: potentially need @encodes for these!
5512 return ' ';
5513
5514 case BuiltinType::ObjCId:
5515 case BuiltinType::ObjCClass:
5516 case BuiltinType::ObjCSel:
5517 llvm_unreachable("@encoding ObjC primitive type");
5518
5519 // OpenCL and placeholder types don't need @encodings.
5520 case BuiltinType::OCLImage1d:
5521 case BuiltinType::OCLImage1dArray:
5522 case BuiltinType::OCLImage1dBuffer:
5523 case BuiltinType::OCLImage2d:
5524 case BuiltinType::OCLImage2dArray:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005525 case BuiltinType::OCLImage2dDepth:
5526 case BuiltinType::OCLImage2dArrayDepth:
5527 case BuiltinType::OCLImage2dMSAA:
5528 case BuiltinType::OCLImage2dArrayMSAA:
5529 case BuiltinType::OCLImage2dMSAADepth:
5530 case BuiltinType::OCLImage2dArrayMSAADepth:
John McCall393a78d2012-12-20 02:45:14 +00005531 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005532 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005533 case BuiltinType::OCLClkEvent:
5534 case BuiltinType::OCLQueue:
5535 case BuiltinType::OCLNDRange:
5536 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005537 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005538 case BuiltinType::Dependent:
5539#define BUILTIN_TYPE(KIND, ID)
5540#define PLACEHOLDER_TYPE(KIND, ID) \
5541 case BuiltinType::KIND:
5542#include "clang/AST/BuiltinTypes.def"
5543 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005544 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005545 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005546}
5547
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005548static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5549 EnumDecl *Enum = ET->getDecl();
5550
5551 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5552 if (!Enum->isFixed())
5553 return 'i';
5554
5555 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005556 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5557 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005558}
5559
Jay Foad39c79802011-01-12 09:06:06 +00005560static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005561 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005562 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005563 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005564 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5565 // The GNU runtime requires more information; bitfields are encoded as b,
5566 // then the offset (in bits) of the first element, then the type of the
5567 // bitfield, then the size in bits. For example, in this structure:
5568 //
5569 // struct
5570 // {
5571 // int integer;
5572 // int flags:2;
5573 // };
5574 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5575 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5576 // information is not especially sensible, but we're stuck with it for
5577 // compatibility with GCC, although providing it breaks anything that
5578 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005579 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005580 const RecordDecl *RD = FD->getParent();
5581 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005582 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005583 if (const EnumType *ET = T->getAs<EnumType>())
5584 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005585 else {
5586 const BuiltinType *BT = T->castAs<BuiltinType>();
5587 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5588 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005589 }
Richard Smithcaf33902011-10-10 18:28:20 +00005590 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005591}
5592
Daniel Dunbar07d07852009-10-18 21:17:35 +00005593// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005594void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5595 bool ExpandPointedToStructures,
5596 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005597 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005598 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005599 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005600 bool StructField,
5601 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005602 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005603 bool EncodePointerToObjCTypedef,
5604 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005605 CanQualType CT = getCanonicalType(T);
5606 switch (CT->getTypeClass()) {
5607 case Type::Builtin:
5608 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005609 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005610 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005611 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5612 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5613 else
5614 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005615 return;
Mike Stump11289f42009-09-09 15:08:12 +00005616
John McCall393a78d2012-12-20 02:45:14 +00005617 case Type::Complex: {
5618 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005619 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005620 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005621 return;
5622 }
John McCall393a78d2012-12-20 02:45:14 +00005623
5624 case Type::Atomic: {
5625 const AtomicType *AT = T->castAs<AtomicType>();
5626 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005627 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005628 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005629 }
John McCall393a78d2012-12-20 02:45:14 +00005630
5631 // encoding for pointer or reference types.
5632 case Type::Pointer:
5633 case Type::LValueReference:
5634 case Type::RValueReference: {
5635 QualType PointeeTy;
5636 if (isa<PointerType>(CT)) {
5637 const PointerType *PT = T->castAs<PointerType>();
5638 if (PT->isObjCSelType()) {
5639 S += ':';
5640 return;
5641 }
5642 PointeeTy = PT->getPointeeType();
5643 } else {
5644 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5645 }
5646
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005647 bool isReadOnly = false;
5648 // For historical/compatibility reasons, the read-only qualifier of the
5649 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5650 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005651 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005652 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005653 if (OutermostType && T.isConstQualified()) {
5654 isReadOnly = true;
5655 S += 'r';
5656 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005657 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005658 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005659 while (P->getAs<PointerType>())
5660 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005661 if (P.isConstQualified()) {
5662 isReadOnly = true;
5663 S += 'r';
5664 }
5665 }
5666 if (isReadOnly) {
5667 // Another legacy compatibility encoding. Some ObjC qualifier and type
5668 // combinations need to be rearranged.
5669 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005670 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005671 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005672 }
Mike Stump11289f42009-09-09 15:08:12 +00005673
Anders Carlssond8499822007-10-29 05:01:08 +00005674 if (PointeeTy->isCharType()) {
5675 // char pointer types should be encoded as '*' unless it is a
5676 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005677 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005678 S += '*';
5679 return;
5680 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005681 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005682 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5683 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5684 S += '#';
5685 return;
5686 }
5687 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5688 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5689 S += '@';
5690 return;
5691 }
5692 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005693 }
Anders Carlssond8499822007-10-29 05:01:08 +00005694 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005695 getLegacyIntegralTypeEncoding(PointeeTy);
5696
Mike Stump11289f42009-09-09 15:08:12 +00005697 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005698 nullptr, false, false, false, false, false, false,
5699 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005700 return;
5701 }
John McCall393a78d2012-12-20 02:45:14 +00005702
5703 case Type::ConstantArray:
5704 case Type::IncompleteArray:
5705 case Type::VariableArray: {
5706 const ArrayType *AT = cast<ArrayType>(CT);
5707
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005708 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005709 // Incomplete arrays are encoded as a pointer to the array element.
5710 S += '^';
5711
Mike Stump11289f42009-09-09 15:08:12 +00005712 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005713 false, ExpandStructures, FD);
5714 } else {
5715 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005716
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005717 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5718 S += llvm::utostr(CAT->getSize().getZExtValue());
5719 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005720 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005721 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5722 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005723 S += '0';
5724 }
Mike Stump11289f42009-09-09 15:08:12 +00005725
5726 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005727 false, ExpandStructures, FD,
5728 false, false, false, false, false, false,
5729 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005730 S += ']';
5731 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005732 return;
5733 }
Mike Stump11289f42009-09-09 15:08:12 +00005734
John McCall393a78d2012-12-20 02:45:14 +00005735 case Type::FunctionNoProto:
5736 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005737 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005738 return;
Mike Stump11289f42009-09-09 15:08:12 +00005739
John McCall393a78d2012-12-20 02:45:14 +00005740 case Type::Record: {
5741 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005742 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005743 // Anonymous structures print as '?'
5744 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5745 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005746 if (ClassTemplateSpecializationDecl *Spec
5747 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5748 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005749 llvm::raw_string_ostream OS(S);
5750 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005751 TemplateArgs.data(),
5752 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005753 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005754 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005755 } else {
5756 S += '?';
5757 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005758 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005759 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005760 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005761 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005762 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005763 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005764 if (FD) {
5765 S += '"';
5766 S += Field->getNameAsString();
5767 S += '"';
5768 }
Mike Stump11289f42009-09-09 15:08:12 +00005769
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005770 // Special case bit-fields.
5771 if (Field->isBitField()) {
5772 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005773 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005774 } else {
5775 QualType qt = Field->getType();
5776 getLegacyIntegralTypeEncoding(qt);
5777 getObjCEncodingForTypeImpl(qt, S, false, true,
5778 FD, /*OutermostType*/false,
5779 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005780 /*StructField*/true,
5781 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005782 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005783 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005784 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005785 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005786 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005787 return;
5788 }
Mike Stump11289f42009-09-09 15:08:12 +00005789
John McCall393a78d2012-12-20 02:45:14 +00005790 case Type::BlockPointer: {
5791 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005792 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005793 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005794 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005795
5796 S += '<';
5797 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005798 getObjCEncodingForTypeImpl(
5799 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5800 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005801 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5802 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005803 // Block self
5804 S += "@?";
5805 // Block parameters
5806 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005807 for (const auto &I : FPT->param_types())
5808 getObjCEncodingForTypeImpl(
5809 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5810 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005811 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5812 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005813 }
5814 S += '>';
5815 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005816 return;
5817 }
Mike Stump11289f42009-09-09 15:08:12 +00005818
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005819 case Type::ObjCObject: {
5820 // hack to match legacy encoding of *id and *Class
5821 QualType Ty = getObjCObjectPointerType(CT);
5822 if (Ty->isObjCIdType()) {
5823 S += "{objc_object=}";
5824 return;
5825 }
5826 else if (Ty->isObjCClassType()) {
5827 S += "{objc_class=}";
5828 return;
5829 }
5830 }
5831
John McCall393a78d2012-12-20 02:45:14 +00005832 case Type::ObjCInterface: {
5833 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005834 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005835 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005836 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005837 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005838 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005839 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005840 DeepCollectObjCIvars(OI, true, Ivars);
5841 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005842 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005843 if (Field->isBitField())
5844 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005845 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005846 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5847 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005848 EncodePointerToObjCTypedef,
5849 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005850 }
5851 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005852 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005853 }
Mike Stump11289f42009-09-09 15:08:12 +00005854
John McCall393a78d2012-12-20 02:45:14 +00005855 case Type::ObjCObjectPointer: {
5856 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005857 if (OPT->isObjCIdType()) {
5858 S += '@';
5859 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005860 }
Mike Stump11289f42009-09-09 15:08:12 +00005861
Steve Narofff0c86112009-10-28 22:03:49 +00005862 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5863 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5864 // Since this is a binary compatibility issue, need to consult with runtime
5865 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005866 S += '#';
5867 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005868 }
Mike Stump11289f42009-09-09 15:08:12 +00005869
Chris Lattnere7cabb92009-07-13 00:10:46 +00005870 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005871 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005872 ExpandPointedToStructures,
5873 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005874 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005875 // Note that we do extended encoding of protocol qualifer list
5876 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005877 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005878 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005879 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005880 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005881 S += '>';
5882 }
5883 S += '"';
5884 }
5885 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005886 }
Mike Stump11289f42009-09-09 15:08:12 +00005887
Chris Lattnere7cabb92009-07-13 00:10:46 +00005888 QualType PointeeTy = OPT->getPointeeType();
5889 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005890 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5891 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005892 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005893 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005894 // {...};
5895 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005896 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005897 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005898 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5899 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5900 DeepCollectObjCIvars(OI, true, Ivars);
5901 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5902 if (cast<FieldDecl>(Ivars[i]) == FD) {
5903 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005904 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005905 S += '}';
5906 return;
5907 }
5908 }
5909 }
Mike Stump11289f42009-09-09 15:08:12 +00005910 getObjCEncodingForTypeImpl(PointeeTy, S,
5911 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005912 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005913 false, false, false, false, false,
5914 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005915 return;
5916 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005917
5918 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005919 if (OPT->getInterfaceDecl() &&
5920 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005921 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005922 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005923 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005924 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005925 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005926 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005927 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005928 S += '"';
5929 }
5930 return;
5931 }
Mike Stump11289f42009-09-09 15:08:12 +00005932
John McCalla9e6e8d2010-05-17 23:56:34 +00005933 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005934 // FIXME: we shoul do better than that. 'M' is available.
5935 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005936 // This matches gcc's encoding, even though technically it is insufficient.
5937 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005938 case Type::Vector:
5939 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005940 // Until we have a coherent encoding of these three types, issue warning.
5941 { if (NotEncodedT)
5942 *NotEncodedT = T;
5943 return;
5944 }
5945
5946 // We could see an undeduced auto type here during error recovery.
5947 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005948 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005949 return;
5950
Xiuli Pan9c14e282016-01-09 12:53:17 +00005951 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00005952#define ABSTRACT_TYPE(KIND, BASE)
5953#define TYPE(KIND, BASE)
5954#define DEPENDENT_TYPE(KIND, BASE) \
5955 case Type::KIND:
5956#define NON_CANONICAL_TYPE(KIND, BASE) \
5957 case Type::KIND:
5958#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5959 case Type::KIND:
5960#include "clang/AST/TypeNodes.def"
5961 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005962 }
John McCall393a78d2012-12-20 02:45:14 +00005963 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005964}
5965
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005966void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5967 std::string &S,
5968 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005969 bool includeVBases,
5970 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005971 assert(RDecl && "Expected non-null RecordDecl");
5972 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00005973 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005974 return;
5975
5976 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5977 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5978 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5979
5980 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005981 for (const auto &BI : CXXRec->bases()) {
5982 if (!BI.isVirtual()) {
5983 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005984 if (base->isEmpty())
5985 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005986 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005987 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5988 std::make_pair(offs, base));
5989 }
5990 }
5991 }
5992
5993 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00005994 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005995 uint64_t offs = layout.getFieldOffset(i);
5996 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00005997 std::make_pair(offs, Field));
5998 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005999 }
6000
6001 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006002 for (const auto &BI : CXXRec->vbases()) {
6003 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006004 if (base->isEmpty())
6005 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006006 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006007 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6008 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006009 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6010 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006011 }
6012 }
6013
6014 CharUnits size;
6015 if (CXXRec) {
6016 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6017 } else {
6018 size = layout.getSize();
6019 }
6020
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006021#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006022 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006023#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006024 std::multimap<uint64_t, NamedDecl *>::iterator
6025 CurLayObj = FieldOrBaseOffsets.begin();
6026
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006027 if (CXXRec && CXXRec->isDynamicClass() &&
6028 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006029 if (FD) {
6030 S += "\"_vptr$";
6031 std::string recname = CXXRec->getNameAsString();
6032 if (recname.empty()) recname = "?";
6033 S += recname;
6034 S += '"';
6035 }
6036 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006037#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006038 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006039#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006040 }
6041
6042 if (!RDecl->hasFlexibleArrayMember()) {
6043 // Mark the end of the structure.
6044 uint64_t offs = toBits(size);
6045 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006046 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006047 }
6048
6049 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006050#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006051 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006052 if (CurOffs < CurLayObj->first) {
6053 uint64_t padding = CurLayObj->first - CurOffs;
6054 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6055 // packing/alignment of members is different that normal, in which case
6056 // the encoding will be out-of-sync with the real layout.
6057 // If the runtime switches to just consider the size of types without
6058 // taking into account alignment, we could make padding explicit in the
6059 // encoding (e.g. using arrays of chars). The encoding strings would be
6060 // longer then though.
6061 CurOffs += padding;
6062 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006063#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006064
6065 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006066 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006067 break; // reached end of structure.
6068
6069 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6070 // We expand the bases without their virtual bases since those are going
6071 // in the initial structure. Note that this differs from gcc which
6072 // expands virtual bases each time one is encountered in the hierarchy,
6073 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006074 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6075 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006076 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006077#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006078 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006079#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006080 } else {
6081 FieldDecl *field = cast<FieldDecl>(dcl);
6082 if (FD) {
6083 S += '"';
6084 S += field->getNameAsString();
6085 S += '"';
6086 }
6087
6088 if (field->isBitField()) {
6089 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006090#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006091 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006092#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006093 } else {
6094 QualType qt = field->getType();
6095 getLegacyIntegralTypeEncoding(qt);
6096 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6097 /*OutermostType*/false,
6098 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006099 /*StructField*/true,
6100 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006101#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006102 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006103#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006104 }
6105 }
6106 }
6107}
6108
Mike Stump11289f42009-09-09 15:08:12 +00006109void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006110 std::string& S) const {
6111 if (QT & Decl::OBJC_TQ_In)
6112 S += 'n';
6113 if (QT & Decl::OBJC_TQ_Inout)
6114 S += 'N';
6115 if (QT & Decl::OBJC_TQ_Out)
6116 S += 'o';
6117 if (QT & Decl::OBJC_TQ_Bycopy)
6118 S += 'O';
6119 if (QT & Decl::OBJC_TQ_Byref)
6120 S += 'R';
6121 if (QT & Decl::OBJC_TQ_Oneway)
6122 S += 'V';
6123}
6124
Douglas Gregor3ea72692011-08-12 05:46:01 +00006125TypedefDecl *ASTContext::getObjCIdDecl() const {
6126 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006127 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006128 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006129 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006130 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006131 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006132}
6133
Douglas Gregor52e02802011-08-12 06:17:30 +00006134TypedefDecl *ASTContext::getObjCSelDecl() const {
6135 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006136 QualType T = getPointerType(ObjCBuiltinSelTy);
6137 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006138 }
6139 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006140}
6141
Douglas Gregor0a586182011-08-12 05:59:41 +00006142TypedefDecl *ASTContext::getObjCClassDecl() const {
6143 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006144 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006145 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006146 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006147 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006148 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006149}
6150
Douglas Gregord53ae832012-01-17 18:09:05 +00006151ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6152 if (!ObjCProtocolClassDecl) {
6153 ObjCProtocolClassDecl
6154 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6155 SourceLocation(),
6156 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006157 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006158 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006159 SourceLocation(), true);
6160 }
6161
6162 return ObjCProtocolClassDecl;
6163}
6164
Meador Inge5d3fb222012-06-16 03:34:49 +00006165//===----------------------------------------------------------------------===//
6166// __builtin_va_list Construction Functions
6167//===----------------------------------------------------------------------===//
6168
Charles Davisc7d5c942015-09-17 20:55:33 +00006169static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6170 StringRef Name) {
6171 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006172 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006173 return Context->buildImplicitTypedef(T, Name);
6174}
6175
6176static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6177 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6178}
6179
6180static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6181 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006182}
6183
6184static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6185 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006186 QualType T = Context->getPointerType(Context->VoidTy);
6187 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006188}
6189
Tim Northover9bb857a2013-01-31 12:13:10 +00006190static TypedefDecl *
6191CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006192 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006193 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006194 if (Context->getLangOpts().CPlusPlus) {
6195 // namespace std { struct __va_list {
6196 NamespaceDecl *NS;
6197 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6198 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006199 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006200 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006201 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006202 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006203 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006204 }
6205
6206 VaListTagDecl->startDefinition();
6207
6208 const size_t NumFields = 5;
6209 QualType FieldTypes[NumFields];
6210 const char *FieldNames[NumFields];
6211
6212 // void *__stack;
6213 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6214 FieldNames[0] = "__stack";
6215
6216 // void *__gr_top;
6217 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6218 FieldNames[1] = "__gr_top";
6219
6220 // void *__vr_top;
6221 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6222 FieldNames[2] = "__vr_top";
6223
6224 // int __gr_offs;
6225 FieldTypes[3] = Context->IntTy;
6226 FieldNames[3] = "__gr_offs";
6227
6228 // int __vr_offs;
6229 FieldTypes[4] = Context->IntTy;
6230 FieldNames[4] = "__vr_offs";
6231
6232 // Create fields
6233 for (unsigned i = 0; i < NumFields; ++i) {
6234 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6235 VaListTagDecl,
6236 SourceLocation(),
6237 SourceLocation(),
6238 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006239 FieldTypes[i], /*TInfo=*/nullptr,
6240 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006241 /*Mutable=*/false,
6242 ICIS_NoInit);
6243 Field->setAccess(AS_public);
6244 VaListTagDecl->addDecl(Field);
6245 }
6246 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006247 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006248 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006249
6250 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006251 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006252}
6253
Meador Inge5d3fb222012-06-16 03:34:49 +00006254static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6255 // typedef struct __va_list_tag {
6256 RecordDecl *VaListTagDecl;
6257
Alp Toker2dea15b2013-12-17 01:22:38 +00006258 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006259 VaListTagDecl->startDefinition();
6260
6261 const size_t NumFields = 5;
6262 QualType FieldTypes[NumFields];
6263 const char *FieldNames[NumFields];
6264
6265 // unsigned char gpr;
6266 FieldTypes[0] = Context->UnsignedCharTy;
6267 FieldNames[0] = "gpr";
6268
6269 // unsigned char fpr;
6270 FieldTypes[1] = Context->UnsignedCharTy;
6271 FieldNames[1] = "fpr";
6272
6273 // unsigned short reserved;
6274 FieldTypes[2] = Context->UnsignedShortTy;
6275 FieldNames[2] = "reserved";
6276
6277 // void* overflow_arg_area;
6278 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6279 FieldNames[3] = "overflow_arg_area";
6280
6281 // void* reg_save_area;
6282 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6283 FieldNames[4] = "reg_save_area";
6284
6285 // Create fields
6286 for (unsigned i = 0; i < NumFields; ++i) {
6287 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6288 SourceLocation(),
6289 SourceLocation(),
6290 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006291 FieldTypes[i], /*TInfo=*/nullptr,
6292 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006293 /*Mutable=*/false,
6294 ICIS_NoInit);
6295 Field->setAccess(AS_public);
6296 VaListTagDecl->addDecl(Field);
6297 }
6298 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006299 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006300 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6301
6302 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006303 TypedefDecl *VaListTagTypedefDecl =
6304 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6305
Meador Inge5d3fb222012-06-16 03:34:49 +00006306 QualType VaListTagTypedefType =
6307 Context->getTypedefType(VaListTagTypedefDecl);
6308
6309 // typedef __va_list_tag __builtin_va_list[1];
6310 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6311 QualType VaListTagArrayType
6312 = Context->getConstantArrayType(VaListTagTypedefType,
6313 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006314 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006315}
6316
6317static TypedefDecl *
6318CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006319 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006320 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006321 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006322 VaListTagDecl->startDefinition();
6323
6324 const size_t NumFields = 4;
6325 QualType FieldTypes[NumFields];
6326 const char *FieldNames[NumFields];
6327
6328 // unsigned gp_offset;
6329 FieldTypes[0] = Context->UnsignedIntTy;
6330 FieldNames[0] = "gp_offset";
6331
6332 // unsigned fp_offset;
6333 FieldTypes[1] = Context->UnsignedIntTy;
6334 FieldNames[1] = "fp_offset";
6335
6336 // void* overflow_arg_area;
6337 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6338 FieldNames[2] = "overflow_arg_area";
6339
6340 // void* reg_save_area;
6341 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6342 FieldNames[3] = "reg_save_area";
6343
6344 // Create fields
6345 for (unsigned i = 0; i < NumFields; ++i) {
6346 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6347 VaListTagDecl,
6348 SourceLocation(),
6349 SourceLocation(),
6350 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006351 FieldTypes[i], /*TInfo=*/nullptr,
6352 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006353 /*Mutable=*/false,
6354 ICIS_NoInit);
6355 Field->setAccess(AS_public);
6356 VaListTagDecl->addDecl(Field);
6357 }
6358 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006359 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006360 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6361
Richard Smith9b88a4c2015-07-27 05:40:23 +00006362 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006363
Richard Smith9b88a4c2015-07-27 05:40:23 +00006364 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006365 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006366 QualType VaListTagArrayType =
6367 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006368 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006369}
6370
6371static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6372 // typedef int __builtin_va_list[4];
6373 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6374 QualType IntArrayType
6375 = Context->getConstantArrayType(Context->IntTy,
6376 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006377 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006378}
6379
Logan Chien57086ce2012-10-10 06:56:20 +00006380static TypedefDecl *
6381CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006382 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006383 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006384 if (Context->getLangOpts().CPlusPlus) {
6385 // namespace std { struct __va_list {
6386 NamespaceDecl *NS;
6387 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6388 Context->getTranslationUnitDecl(),
6389 /*Inline*/false, SourceLocation(),
6390 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006391 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006392 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006393 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006394 }
6395
6396 VaListDecl->startDefinition();
6397
6398 // void * __ap;
6399 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6400 VaListDecl,
6401 SourceLocation(),
6402 SourceLocation(),
6403 &Context->Idents.get("__ap"),
6404 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006405 /*TInfo=*/nullptr,
6406 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006407 /*Mutable=*/false,
6408 ICIS_NoInit);
6409 Field->setAccess(AS_public);
6410 VaListDecl->addDecl(Field);
6411
6412 // };
6413 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006414 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006415
6416 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006417 QualType T = Context->getRecordType(VaListDecl);
6418 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006419}
6420
Ulrich Weigand47445072013-05-06 16:26:41 +00006421static TypedefDecl *
6422CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006423 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006424 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006425 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006426 VaListTagDecl->startDefinition();
6427
6428 const size_t NumFields = 4;
6429 QualType FieldTypes[NumFields];
6430 const char *FieldNames[NumFields];
6431
6432 // long __gpr;
6433 FieldTypes[0] = Context->LongTy;
6434 FieldNames[0] = "__gpr";
6435
6436 // long __fpr;
6437 FieldTypes[1] = Context->LongTy;
6438 FieldNames[1] = "__fpr";
6439
6440 // void *__overflow_arg_area;
6441 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6442 FieldNames[2] = "__overflow_arg_area";
6443
6444 // void *__reg_save_area;
6445 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6446 FieldNames[3] = "__reg_save_area";
6447
6448 // Create fields
6449 for (unsigned i = 0; i < NumFields; ++i) {
6450 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6451 VaListTagDecl,
6452 SourceLocation(),
6453 SourceLocation(),
6454 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006455 FieldTypes[i], /*TInfo=*/nullptr,
6456 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006457 /*Mutable=*/false,
6458 ICIS_NoInit);
6459 Field->setAccess(AS_public);
6460 VaListTagDecl->addDecl(Field);
6461 }
6462 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006463 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006464 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006465
Richard Smith9b88a4c2015-07-27 05:40:23 +00006466 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006467
6468 // typedef __va_list_tag __builtin_va_list[1];
6469 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006470 QualType VaListTagArrayType =
6471 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006472
Alp Toker56b5cc92013-12-15 10:36:26 +00006473 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006474}
6475
Meador Inge5d3fb222012-06-16 03:34:49 +00006476static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6477 TargetInfo::BuiltinVaListKind Kind) {
6478 switch (Kind) {
6479 case TargetInfo::CharPtrBuiltinVaList:
6480 return CreateCharPtrBuiltinVaListDecl(Context);
6481 case TargetInfo::VoidPtrBuiltinVaList:
6482 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006483 case TargetInfo::AArch64ABIBuiltinVaList:
6484 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006485 case TargetInfo::PowerABIBuiltinVaList:
6486 return CreatePowerABIBuiltinVaListDecl(Context);
6487 case TargetInfo::X86_64ABIBuiltinVaList:
6488 return CreateX86_64ABIBuiltinVaListDecl(Context);
6489 case TargetInfo::PNaClABIBuiltinVaList:
6490 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006491 case TargetInfo::AAPCSABIBuiltinVaList:
6492 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006493 case TargetInfo::SystemZBuiltinVaList:
6494 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006495 }
6496
6497 llvm_unreachable("Unhandled __builtin_va_list type kind");
6498}
6499
6500TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006501 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006502 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006503 assert(BuiltinVaListDecl->isImplicit());
6504 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006505
6506 return BuiltinVaListDecl;
6507}
6508
Richard Smith9b88a4c2015-07-27 05:40:23 +00006509Decl *ASTContext::getVaListTagDecl() const {
6510 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006511 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006512 if (!VaListTagDecl)
6513 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006514
Richard Smith9b88a4c2015-07-27 05:40:23 +00006515 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006516}
6517
Charles Davisc7d5c942015-09-17 20:55:33 +00006518TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6519 if (!BuiltinMSVaListDecl)
6520 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6521
6522 return BuiltinMSVaListDecl;
6523}
6524
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006525void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006526 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006527 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006528
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006529 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006530}
6531
John McCalld28ae272009-12-02 08:04:21 +00006532/// \brief Retrieve the template name that corresponds to a non-empty
6533/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006534TemplateName
6535ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6536 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006537 unsigned size = End - Begin;
6538 assert(size > 1 && "set is not overloaded!");
6539
6540 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6541 size * sizeof(FunctionTemplateDecl*));
6542 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6543
6544 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006545 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006546 NamedDecl *D = *I;
6547 assert(isa<FunctionTemplateDecl>(D) ||
6548 (isa<UsingShadowDecl>(D) &&
6549 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6550 *Storage++ = D;
6551 }
6552
6553 return TemplateName(OT);
6554}
6555
Douglas Gregordc572a32009-03-30 22:58:21 +00006556/// \brief Retrieve the template name that represents a qualified
6557/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006558TemplateName
6559ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6560 bool TemplateKeyword,
6561 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006562 assert(NNS && "Missing nested-name-specifier in qualified template name");
6563
Douglas Gregorc42075a2010-02-04 18:10:26 +00006564 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006565 llvm::FoldingSetNodeID ID;
6566 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6567
Craig Topper36250ad2014-05-12 05:36:57 +00006568 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006569 QualifiedTemplateName *QTN =
6570 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6571 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006572 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6573 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006574 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6575 }
6576
6577 return TemplateName(QTN);
6578}
6579
6580/// \brief Retrieve the template name that represents a dependent
6581/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006582TemplateName
6583ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6584 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006585 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006586 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006587
6588 llvm::FoldingSetNodeID ID;
6589 DependentTemplateName::Profile(ID, NNS, Name);
6590
Craig Topper36250ad2014-05-12 05:36:57 +00006591 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006592 DependentTemplateName *QTN =
6593 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6594
6595 if (QTN)
6596 return TemplateName(QTN);
6597
6598 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6599 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006600 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6601 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006602 } else {
6603 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006604 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6605 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006606 DependentTemplateName *CheckQTN =
6607 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6608 assert(!CheckQTN && "Dependent type name canonicalization broken");
6609 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006610 }
6611
6612 DependentTemplateNames.InsertNode(QTN, InsertPos);
6613 return TemplateName(QTN);
6614}
6615
Douglas Gregor71395fa2009-11-04 00:56:37 +00006616/// \brief Retrieve the template name that represents a dependent
6617/// template name such as \c MetaFun::template operator+.
6618TemplateName
6619ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006620 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006621 assert((!NNS || NNS->isDependent()) &&
6622 "Nested name specifier must be dependent");
6623
6624 llvm::FoldingSetNodeID ID;
6625 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006626
6627 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006628 DependentTemplateName *QTN
6629 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006630
6631 if (QTN)
6632 return TemplateName(QTN);
6633
6634 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6635 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006636 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6637 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006638 } else {
6639 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006640 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6641 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006642
6643 DependentTemplateName *CheckQTN
6644 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6645 assert(!CheckQTN && "Dependent template name canonicalization broken");
6646 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006647 }
6648
6649 DependentTemplateNames.InsertNode(QTN, InsertPos);
6650 return TemplateName(QTN);
6651}
6652
Douglas Gregor5590be02011-01-15 06:45:20 +00006653TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006654ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6655 TemplateName replacement) const {
6656 llvm::FoldingSetNodeID ID;
6657 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006658
6659 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006660 SubstTemplateTemplateParmStorage *subst
6661 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6662
6663 if (!subst) {
6664 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6665 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6666 }
6667
6668 return TemplateName(subst);
6669}
6670
6671TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006672ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6673 const TemplateArgument &ArgPack) const {
6674 ASTContext &Self = const_cast<ASTContext &>(*this);
6675 llvm::FoldingSetNodeID ID;
6676 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006677
6678 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006679 SubstTemplateTemplateParmPackStorage *Subst
6680 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6681
6682 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006683 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006684 ArgPack.pack_size(),
6685 ArgPack.pack_begin());
6686 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6687 }
6688
6689 return TemplateName(Subst);
6690}
6691
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006692/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006693/// TargetInfo, produce the corresponding type. The unsigned @p Type
6694/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006695CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006696 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006697 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006698 case TargetInfo::SignedChar: return SignedCharTy;
6699 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006700 case TargetInfo::SignedShort: return ShortTy;
6701 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6702 case TargetInfo::SignedInt: return IntTy;
6703 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6704 case TargetInfo::SignedLong: return LongTy;
6705 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6706 case TargetInfo::SignedLongLong: return LongLongTy;
6707 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6708 }
6709
David Blaikie83d382b2011-09-23 05:06:16 +00006710 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006711}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006712
6713//===----------------------------------------------------------------------===//
6714// Type Predicates.
6715//===----------------------------------------------------------------------===//
6716
Fariborz Jahanian96207692009-02-18 21:49:28 +00006717/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6718/// garbage collection attribute.
6719///
John McCall553d45a2011-01-12 00:34:59 +00006720Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006721 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006722 return Qualifiers::GCNone;
6723
David Blaikiebbafb8a2012-03-11 07:00:24 +00006724 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006725 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6726
6727 // Default behaviour under objective-C's gc is for ObjC pointers
6728 // (or pointers to them) be treated as though they were declared
6729 // as __strong.
6730 if (GCAttrs == Qualifiers::GCNone) {
6731 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6732 return Qualifiers::Strong;
6733 else if (Ty->isPointerType())
6734 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6735 } else {
6736 // It's not valid to set GC attributes on anything that isn't a
6737 // pointer.
6738#ifndef NDEBUG
6739 QualType CT = Ty->getCanonicalTypeInternal();
6740 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6741 CT = AT->getElementType();
6742 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6743#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006744 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006745 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006746}
6747
Chris Lattner49af6a42008-04-07 06:51:04 +00006748//===----------------------------------------------------------------------===//
6749// Type Compatibility Testing
6750//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006751
Mike Stump11289f42009-09-09 15:08:12 +00006752/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006753/// compatible.
6754static bool areCompatVectorTypes(const VectorType *LHS,
6755 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006756 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006757 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006758 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006759}
6760
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006761bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6762 QualType SecondVec) {
6763 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6764 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6765
6766 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6767 return true;
6768
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006769 // Treat Neon vector types and most AltiVec vector types as if they are the
6770 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006771 const VectorType *First = FirstVec->getAs<VectorType>();
6772 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006773 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006774 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006775 First->getVectorKind() != VectorType::AltiVecPixel &&
6776 First->getVectorKind() != VectorType::AltiVecBool &&
6777 Second->getVectorKind() != VectorType::AltiVecPixel &&
6778 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006779 return true;
6780
6781 return false;
6782}
6783
Steve Naroff8e6aee52009-07-23 01:01:38 +00006784//===----------------------------------------------------------------------===//
6785// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6786//===----------------------------------------------------------------------===//
6787
6788/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6789/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006790bool
6791ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6792 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006793 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006794 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006795 for (auto *PI : rProto->protocols())
6796 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006797 return true;
6798 return false;
6799}
6800
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006801/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6802/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006803bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6804 QualType rhs) {
6805 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6806 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6807 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6808
Aaron Ballman83731462014-03-17 16:14:00 +00006809 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006810 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006811 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006812 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6813 match = true;
6814 break;
6815 }
6816 }
6817 if (!match)
6818 return false;
6819 }
6820 return true;
6821}
6822
Steve Naroff8e6aee52009-07-23 01:01:38 +00006823/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6824/// ObjCQualifiedIDType.
6825bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6826 bool compare) {
6827 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006828 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006829 lhs->isObjCIdType() || lhs->isObjCClassType())
6830 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006831 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006832 rhs->isObjCIdType() || rhs->isObjCClassType())
6833 return true;
6834
6835 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006836 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006837
Steve Naroff8e6aee52009-07-23 01:01:38 +00006838 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006839
Steve Naroff8e6aee52009-07-23 01:01:38 +00006840 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006841 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006842 // make sure we check the class hierarchy.
6843 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006844 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006845 // when comparing an id<P> on lhs with a static type on rhs,
6846 // see if static class implements all of id's protocols, directly or
6847 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006848 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006849 return false;
6850 }
6851 }
6852 // If there are no qualifiers and no interface, we have an 'id'.
6853 return true;
6854 }
Mike Stump11289f42009-09-09 15:08:12 +00006855 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006856 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006857 bool match = false;
6858
6859 // when comparing an id<P> on lhs with a static type on rhs,
6860 // see if static class implements all of id's protocols, directly or
6861 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006862 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006863 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6864 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6865 match = true;
6866 break;
6867 }
6868 }
Mike Stump11289f42009-09-09 15:08:12 +00006869 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006870 // make sure we check the class hierarchy.
6871 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006872 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006873 // when comparing an id<P> on lhs with a static type on rhs,
6874 // see if static class implements all of id's protocols, directly or
6875 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006876 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006877 match = true;
6878 break;
6879 }
6880 }
6881 }
6882 if (!match)
6883 return false;
6884 }
Mike Stump11289f42009-09-09 15:08:12 +00006885
Steve Naroff8e6aee52009-07-23 01:01:38 +00006886 return true;
6887 }
Mike Stump11289f42009-09-09 15:08:12 +00006888
Steve Naroff8e6aee52009-07-23 01:01:38 +00006889 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6890 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6891
Mike Stump11289f42009-09-09 15:08:12 +00006892 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006893 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006894 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006895 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006896 bool match = false;
6897
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006898 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006899 // see if static class implements all of id's protocols, directly or
6900 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006901 // First, lhs protocols in the qualifier list must be found, direct
6902 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006903 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006904 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6905 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6906 match = true;
6907 break;
6908 }
6909 }
6910 if (!match)
6911 return false;
6912 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006913
6914 // Static class's protocols, or its super class or category protocols
6915 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6916 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6917 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6918 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6919 // This is rather dubious but matches gcc's behavior. If lhs has
6920 // no type qualifier and its class has no static protocol(s)
6921 // assume that it is mismatch.
6922 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6923 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006924 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006925 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006926 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006927 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6928 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6929 match = true;
6930 break;
6931 }
6932 }
6933 if (!match)
6934 return false;
6935 }
6936 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006937 return true;
6938 }
6939 return false;
6940}
6941
Eli Friedman47f77112008-08-22 00:56:42 +00006942/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006943/// compatible for assignment from RHS to LHS. This handles validation of any
6944/// protocol qualifiers on the LHS or RHS.
6945///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006946bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6947 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006948 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6949 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6950
Steve Naroff1329fa02009-07-15 18:40:39 +00006951 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006952 if (LHS->isObjCUnqualifiedIdOrClass() ||
6953 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006954 return true;
6955
Douglas Gregorab209d82015-07-07 03:58:42 +00006956 // Function object that propagates a successful result or handles
6957 // __kindof types.
6958 auto finish = [&](bool succeeded) -> bool {
6959 if (succeeded)
6960 return true;
6961
6962 if (!RHS->isKindOfType())
6963 return false;
6964
6965 // Strip off __kindof and protocol qualifiers, then check whether
6966 // we can assign the other way.
6967 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6968 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6969 };
6970
6971 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6972 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6973 QualType(RHSOPT,0),
6974 false));
6975 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006976
Douglas Gregorab209d82015-07-07 03:58:42 +00006977 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6978 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6979 QualType(RHSOPT,0)));
6980 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006981
John McCall8b07ec22010-05-15 11:32:37 +00006982 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006983 if (LHS->getInterface() && RHS->getInterface()) {
6984 return finish(canAssignObjCInterfaces(LHS, RHS));
6985 }
Mike Stump11289f42009-09-09 15:08:12 +00006986
Steve Naroff8e6aee52009-07-23 01:01:38 +00006987 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006988}
6989
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006990/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006991/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006992/// arguments in block literals. When passed as arguments, passing 'A*' where
6993/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6994/// not OK. For the return type, the opposite is not OK.
6995bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6996 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006997 const ObjCObjectPointerType *RHSOPT,
6998 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00006999
7000 // Function object that propagates a successful result or handles
7001 // __kindof types.
7002 auto finish = [&](bool succeeded) -> bool {
7003 if (succeeded)
7004 return true;
7005
7006 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7007 if (!Expected->isKindOfType())
7008 return false;
7009
7010 // Strip off __kindof and protocol qualifiers, then check whether
7011 // we can assign the other way.
7012 return canAssignObjCInterfacesInBlockPointer(
7013 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7014 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7015 BlockReturnType);
7016 };
7017
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007018 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007019 return true;
7020
7021 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007022 return finish(RHSOPT->isObjCBuiltinType() ||
7023 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007024 }
7025
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007026 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007027 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7028 QualType(RHSOPT,0),
7029 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007030
7031 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7032 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7033 if (LHS && RHS) { // We have 2 user-defined types.
7034 if (LHS != RHS) {
7035 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007036 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007037 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007038 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007039 }
7040 else
7041 return true;
7042 }
7043 return false;
7044}
7045
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007046/// Comparison routine for Objective-C protocols to be used with
7047/// llvm::array_pod_sort.
7048static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7049 ObjCProtocolDecl * const *rhs) {
7050 return (*lhs)->getName().compare((*rhs)->getName());
7051
7052}
7053
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007054/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007055/// of protocols inherited from two distinct objective-c pointer objects with
7056/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007057/// It is used to build composite qualifier list of the composite type of
7058/// the conditional expression involving two objective-c pointer objects.
7059static
7060void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007061 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007062 const ObjCObjectPointerType *LHSOPT,
7063 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007064 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007065
John McCall8b07ec22010-05-15 11:32:37 +00007066 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7067 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7068 assert(LHS->getInterface() && "LHS must have an interface base");
7069 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007070
7071 // Add all of the protocols for the LHS.
7072 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7073
7074 // Start with the protocol qualifiers.
7075 for (auto proto : LHS->quals()) {
7076 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007077 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007078
7079 // Also add the protocols associated with the LHS interface.
7080 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7081
7082 // Add all of the protocls for the RHS.
7083 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7084
7085 // Start with the protocol qualifiers.
7086 for (auto proto : RHS->quals()) {
7087 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007088 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007089
7090 // Also add the protocols associated with the RHS interface.
7091 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7092
7093 // Compute the intersection of the collected protocol sets.
7094 for (auto proto : LHSProtocolSet) {
7095 if (RHSProtocolSet.count(proto))
7096 IntersectionSet.push_back(proto);
7097 }
7098
7099 // Compute the set of protocols that is implied by either the common type or
7100 // the protocols within the intersection.
7101 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7102 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7103
7104 // Remove any implied protocols from the list of inherited protocols.
7105 if (!ImpliedProtocols.empty()) {
7106 IntersectionSet.erase(
7107 std::remove_if(IntersectionSet.begin(),
7108 IntersectionSet.end(),
7109 [&](ObjCProtocolDecl *proto) -> bool {
7110 return ImpliedProtocols.count(proto) > 0;
7111 }),
7112 IntersectionSet.end());
7113 }
7114
7115 // Sort the remaining protocols by name.
7116 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7117 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007118}
7119
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007120/// Determine whether the first type is a subtype of the second.
7121static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7122 QualType rhs) {
7123 // Common case: two object pointers.
7124 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7125 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7126 if (lhsOPT && rhsOPT)
7127 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7128
7129 // Two block pointers.
7130 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7131 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7132 if (lhsBlock && rhsBlock)
7133 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7134
7135 // If either is an unqualified 'id' and the other is a block, it's
7136 // acceptable.
7137 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7138 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7139 return true;
7140
7141 return false;
7142}
7143
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007144// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007145static bool sameObjCTypeArgs(ASTContext &ctx,
7146 const ObjCInterfaceDecl *iface,
7147 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007148 ArrayRef<QualType> rhsArgs,
7149 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007150 if (lhsArgs.size() != rhsArgs.size())
7151 return false;
7152
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007153 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007154 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007155 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7156 continue;
7157
7158 switch (typeParams->begin()[i]->getVariance()) {
7159 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007160 if (!stripKindOf ||
7161 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7162 rhsArgs[i].stripObjCKindOfType(ctx))) {
7163 return false;
7164 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007165 break;
7166
7167 case ObjCTypeParamVariance::Covariant:
7168 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7169 return false;
7170 break;
7171
7172 case ObjCTypeParamVariance::Contravariant:
7173 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7174 return false;
7175 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007176 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007177 }
7178
7179 return true;
7180}
7181
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007182QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007183 const ObjCObjectPointerType *Lptr,
7184 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007185 const ObjCObjectType *LHS = Lptr->getObjectType();
7186 const ObjCObjectType *RHS = Rptr->getObjectType();
7187 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7188 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007189
7190 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007191 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007192
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007193 // Follow the left-hand side up the class hierarchy until we either hit a
7194 // root or find the RHS. Record the ancestors in case we don't find it.
7195 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7196 LHSAncestors;
7197 while (true) {
7198 // Record this ancestor. We'll need this if the common type isn't in the
7199 // path from the LHS to the root.
7200 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007201
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007202 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7203 // Get the type arguments.
7204 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7205 bool anyChanges = false;
7206 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7207 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007208 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7209 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007210 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007211 return QualType();
7212 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7213 // If only one has type arguments, the result will not have type
7214 // arguments.
7215 LHSTypeArgs = { };
7216 anyChanges = true;
7217 }
7218
7219 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007220 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007221 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7222 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007223 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007224 anyChanges = true;
7225
7226 // If anything in the LHS will have changed, build a new result type.
7227 if (anyChanges) {
7228 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007229 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7230 LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007231 return getObjCObjectPointerType(Result);
7232 }
7233
7234 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007235 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007236
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007237 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007238 QualType LHSSuperType = LHS->getSuperClassType();
7239 if (LHSSuperType.isNull())
7240 break;
7241
7242 LHS = LHSSuperType->castAs<ObjCObjectType>();
7243 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007244
7245 // We didn't find anything by following the LHS to its root; now check
7246 // the RHS against the cached set of ancestors.
7247 while (true) {
7248 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7249 if (KnownLHS != LHSAncestors.end()) {
7250 LHS = KnownLHS->second;
7251
7252 // Get the type arguments.
7253 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7254 bool anyChanges = false;
7255 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7256 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007257 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7258 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007259 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007260 return QualType();
7261 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7262 // If only one has type arguments, the result will not have type
7263 // arguments.
7264 RHSTypeArgs = { };
7265 anyChanges = true;
7266 }
7267
7268 // Compute the intersection of protocols.
7269 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7270 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7271 Protocols);
7272 if (!Protocols.empty())
7273 anyChanges = true;
7274
7275 if (anyChanges) {
7276 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007277 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7278 RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007279 return getObjCObjectPointerType(Result);
7280 }
7281
7282 return getObjCObjectPointerType(QualType(RHS, 0));
7283 }
7284
7285 // Find the superclass of the RHS.
7286 QualType RHSSuperType = RHS->getSuperClassType();
7287 if (RHSSuperType.isNull())
7288 break;
7289
7290 RHS = RHSSuperType->castAs<ObjCObjectType>();
7291 }
7292
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007293 return QualType();
7294}
7295
John McCall8b07ec22010-05-15 11:32:37 +00007296bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7297 const ObjCObjectType *RHS) {
7298 assert(LHS->getInterface() && "LHS is not an interface type");
7299 assert(RHS->getInterface() && "RHS is not an interface type");
7300
Chris Lattner49af6a42008-04-07 06:51:04 +00007301 // Verify that the base decls are compatible: the RHS must be a subclass of
7302 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007303 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7304 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7305 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007306 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007307
Douglas Gregore83b9562015-07-07 03:57:53 +00007308 // If the LHS has protocol qualifiers, determine whether all of them are
7309 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7310 // LHS).
7311 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007312 // OK if conversion of LHS to SuperClass results in narrowing of types
7313 // ; i.e., SuperClass may implement at least one of the protocols
7314 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7315 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7316 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7317 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7318 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7319 // qualifiers.
7320 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007321 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007322 // If there is no protocols associated with RHS, it is not a match.
7323 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007324 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007325
7326 for (const auto *LHSProto : LHS->quals()) {
7327 bool SuperImplementsProtocol = false;
7328 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7329 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7330 SuperImplementsProtocol = true;
7331 break;
7332 }
7333 if (!SuperImplementsProtocol)
7334 return false;
7335 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007336 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007337
7338 // If the LHS is specialized, we may need to check type arguments.
7339 if (LHS->isSpecialized()) {
7340 // Follow the superclass chain until we've matched the LHS class in the
7341 // hierarchy. This substitutes type arguments through.
7342 const ObjCObjectType *RHSSuper = RHS;
7343 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7344 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7345
7346 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007347 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007348 !sameObjCTypeArgs(*this, LHS->getInterface(),
7349 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007350 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007351 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007352 }
7353 }
7354
7355 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007356}
7357
Steve Naroffb7605152009-02-12 17:52:19 +00007358bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7359 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007360 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7361 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007362
Steve Naroff7cae42b2009-07-10 23:34:53 +00007363 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007364 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007365
7366 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7367 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007368}
7369
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007370bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7371 return canAssignObjCInterfaces(
7372 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7373 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7374}
7375
Mike Stump11289f42009-09-09 15:08:12 +00007376/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007377/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007378/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007379/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007380bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7381 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007382 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007383 return hasSameType(LHS, RHS);
7384
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007385 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007386}
7387
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007388bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007389 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007390}
7391
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007392bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7393 return !mergeTypes(LHS, RHS, true).isNull();
7394}
7395
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007396/// mergeTransparentUnionType - if T is a transparent union type and a member
7397/// of T is compatible with SubType, return the merged type, else return
7398/// QualType()
7399QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7400 bool OfBlockPointer,
7401 bool Unqualified) {
7402 if (const RecordType *UT = T->getAsUnionType()) {
7403 RecordDecl *UD = UT->getDecl();
7404 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007405 for (const auto *I : UD->fields()) {
7406 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007407 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7408 if (!MT.isNull())
7409 return MT;
7410 }
7411 }
7412 }
7413
7414 return QualType();
7415}
7416
Alp Toker9cacbab2014-01-20 20:26:09 +00007417/// mergeFunctionParameterTypes - merge two types which appear as function
7418/// parameter types
7419QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7420 bool OfBlockPointer,
7421 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007422 // GNU extension: two types are compatible if they appear as a function
7423 // argument, one of the types is a transparent union type and the other
7424 // type is compatible with a union member
7425 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7426 Unqualified);
7427 if (!lmerge.isNull())
7428 return lmerge;
7429
7430 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7431 Unqualified);
7432 if (!rmerge.isNull())
7433 return rmerge;
7434
7435 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7436}
7437
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007438QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007439 bool OfBlockPointer,
7440 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007441 const FunctionType *lbase = lhs->getAs<FunctionType>();
7442 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007443 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7444 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007445 bool allLTypes = true;
7446 bool allRTypes = true;
7447
7448 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007449 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007450 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007451 QualType RHS = rbase->getReturnType();
7452 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007453 bool UnqualifiedResult = Unqualified;
7454 if (!UnqualifiedResult)
7455 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007456 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007457 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007458 else
Alp Toker314cc812014-01-25 16:55:45 +00007459 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007460 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007461 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007462
7463 if (Unqualified)
7464 retType = retType.getUnqualifiedType();
7465
Alp Toker314cc812014-01-25 16:55:45 +00007466 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7467 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007468 if (Unqualified) {
7469 LRetType = LRetType.getUnqualifiedType();
7470 RRetType = RRetType.getUnqualifiedType();
7471 }
7472
7473 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007474 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007475 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007476 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007477
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007478 // FIXME: double check this
7479 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7480 // rbase->getRegParmAttr() != 0 &&
7481 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007482 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7483 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007484
Douglas Gregor8c940862010-01-18 17:14:39 +00007485 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007486 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007487 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007488
John McCall8c6b56f2010-12-15 01:06:38 +00007489 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007490 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7491 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007492 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7493 return QualType();
7494
John McCall31168b02011-06-15 23:02:42 +00007495 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7496 return QualType();
7497
John McCall8c6b56f2010-12-15 01:06:38 +00007498 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7499 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007500
Rafael Espindola8778c282012-11-29 16:09:03 +00007501 if (lbaseInfo.getNoReturn() != NoReturn)
7502 allLTypes = false;
7503 if (rbaseInfo.getNoReturn() != NoReturn)
7504 allRTypes = false;
7505
John McCall31168b02011-06-15 23:02:42 +00007506 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007507
Eli Friedman47f77112008-08-22 00:56:42 +00007508 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007509 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7510 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007511 // Compatible functions must have the same number of parameters
7512 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007513 return QualType();
7514
7515 // Variadic and non-variadic functions aren't compatible
7516 if (lproto->isVariadic() != rproto->isVariadic())
7517 return QualType();
7518
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007519 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7520 return QualType();
7521
John McCall18afab72016-03-01 00:49:02 +00007522 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007523 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007524
7525 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007526 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007527 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7528 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7529 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7530 QualType paramType = mergeFunctionParameterTypes(
7531 lParamType, rParamType, OfBlockPointer, Unqualified);
7532 if (paramType.isNull())
7533 return QualType();
7534
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007535 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007536 paramType = paramType.getUnqualifiedType();
7537
7538 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007539 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007540 lParamType = lParamType.getUnqualifiedType();
7541 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007542 }
Alp Toker601b22c2014-01-21 23:35:24 +00007543
7544 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007545 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007546 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007547 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007548 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007549
Eli Friedman47f77112008-08-22 00:56:42 +00007550 if (allLTypes) return lhs;
7551 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007552
7553 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7554 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007555 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007556 }
7557
7558 if (lproto) allRTypes = false;
7559 if (rproto) allLTypes = false;
7560
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007561 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007562 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007563 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007564 if (proto->isVariadic()) return QualType();
7565 // Check that the types are compatible with the types that
7566 // would result from default argument promotions (C99 6.7.5.3p15).
7567 // The only types actually affected are promotable integer
7568 // types and floats, which would be passed as a different
7569 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007570 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7571 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007572
Eli Friedman448ce402012-08-30 00:44:15 +00007573 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007574 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007575 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7576 paramTy = Enum->getDecl()->getIntegerType();
7577 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007578 return QualType();
7579 }
Alp Toker601b22c2014-01-21 23:35:24 +00007580
7581 if (paramTy->isPromotableIntegerType() ||
7582 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007583 return QualType();
7584 }
7585
7586 if (allLTypes) return lhs;
7587 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007588
7589 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7590 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007591 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007592 }
7593
7594 if (allLTypes) return lhs;
7595 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007596 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007597}
7598
John McCall433c2e62013-03-21 00:10:07 +00007599/// Given that we have an enum type and a non-enum type, try to merge them.
7600static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7601 QualType other, bool isBlockReturnType) {
7602 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7603 // a signed integer type, or an unsigned integer type.
7604 // Compatibility is based on the underlying type, not the promotion
7605 // type.
7606 QualType underlyingType = ET->getDecl()->getIntegerType();
7607 if (underlyingType.isNull()) return QualType();
7608 if (Context.hasSameType(underlyingType, other))
7609 return other;
7610
7611 // In block return types, we're more permissive and accept any
7612 // integral type of the same size.
7613 if (isBlockReturnType && other->isIntegerType() &&
7614 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7615 return other;
7616
7617 return QualType();
7618}
7619
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007620QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007621 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007622 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007623 // C++ [expr]: If an expression initially has the type "reference to T", the
7624 // type is adjusted to "T" prior to any further analysis, the expression
7625 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007626 // expression is an lvalue unless the reference is an rvalue reference and
7627 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007628 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7629 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007630
7631 if (Unqualified) {
7632 LHS = LHS.getUnqualifiedType();
7633 RHS = RHS.getUnqualifiedType();
7634 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007635
Eli Friedman47f77112008-08-22 00:56:42 +00007636 QualType LHSCan = getCanonicalType(LHS),
7637 RHSCan = getCanonicalType(RHS);
7638
7639 // If two types are identical, they are compatible.
7640 if (LHSCan == RHSCan)
7641 return LHS;
7642
John McCall8ccfcb52009-09-24 19:53:00 +00007643 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007644 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7645 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007646 if (LQuals != RQuals) {
7647 // If any of these qualifiers are different, we have a type
7648 // mismatch.
7649 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007650 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7651 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007652 return QualType();
7653
7654 // Exactly one GC qualifier difference is allowed: __strong is
7655 // okay if the other type has no GC qualifier but is an Objective
7656 // C object pointer (i.e. implicitly strong by default). We fix
7657 // this by pretending that the unqualified type was actually
7658 // qualified __strong.
7659 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7660 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7661 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7662
7663 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7664 return QualType();
7665
7666 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7667 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7668 }
7669 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7670 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7671 }
Eli Friedman47f77112008-08-22 00:56:42 +00007672 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007673 }
7674
7675 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007676
Eli Friedmandcca6332009-06-01 01:22:52 +00007677 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7678 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007679
Chris Lattnerfd652912008-01-14 05:45:46 +00007680 // We want to consider the two function types to be the same for these
7681 // comparisons, just force one to the other.
7682 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7683 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007684
7685 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007686 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7687 LHSClass = Type::ConstantArray;
7688 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7689 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007690
John McCall8b07ec22010-05-15 11:32:37 +00007691 // ObjCInterfaces are just specialized ObjCObjects.
7692 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7693 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7694
Nate Begemance4d7fc2008-04-18 23:10:10 +00007695 // Canonicalize ExtVector -> Vector.
7696 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7697 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007698
Chris Lattner95554662008-04-07 05:43:21 +00007699 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007700 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007701 // Note that we only have special rules for turning block enum
7702 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007703 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007704 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007705 }
John McCall9dd450b2009-09-21 23:43:11 +00007706 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007707 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007708 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007709 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007710 if (OfBlockPointer && !BlockReturnType) {
7711 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7712 return LHS;
7713 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7714 return RHS;
7715 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007716
Eli Friedman47f77112008-08-22 00:56:42 +00007717 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007718 }
Eli Friedman47f77112008-08-22 00:56:42 +00007719
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007720 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007721 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007722#define TYPE(Class, Base)
7723#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007724#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007725#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7726#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7727#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007728 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007729
Richard Smith27d807c2013-04-30 13:56:41 +00007730 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007731 case Type::LValueReference:
7732 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007733 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007734 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007735
John McCall8b07ec22010-05-15 11:32:37 +00007736 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007737 case Type::IncompleteArray:
7738 case Type::VariableArray:
7739 case Type::FunctionProto:
7740 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007741 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007742
Chris Lattnerfd652912008-01-14 05:45:46 +00007743 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007744 {
7745 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007746 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7747 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007748 if (Unqualified) {
7749 LHSPointee = LHSPointee.getUnqualifiedType();
7750 RHSPointee = RHSPointee.getUnqualifiedType();
7751 }
7752 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7753 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007754 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007755 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007756 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007757 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007758 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007759 return getPointerType(ResultType);
7760 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007761 case Type::BlockPointer:
7762 {
7763 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007764 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7765 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007766 if (Unqualified) {
7767 LHSPointee = LHSPointee.getUnqualifiedType();
7768 RHSPointee = RHSPointee.getUnqualifiedType();
7769 }
7770 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7771 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007772 if (ResultType.isNull()) return QualType();
7773 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7774 return LHS;
7775 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7776 return RHS;
7777 return getBlockPointerType(ResultType);
7778 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007779 case Type::Atomic:
7780 {
7781 // Merge two pointer types, while trying to preserve typedef info
7782 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7783 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7784 if (Unqualified) {
7785 LHSValue = LHSValue.getUnqualifiedType();
7786 RHSValue = RHSValue.getUnqualifiedType();
7787 }
7788 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7789 Unqualified);
7790 if (ResultType.isNull()) return QualType();
7791 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7792 return LHS;
7793 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7794 return RHS;
7795 return getAtomicType(ResultType);
7796 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007797 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007798 {
7799 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7800 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7801 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7802 return QualType();
7803
7804 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7805 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007806 if (Unqualified) {
7807 LHSElem = LHSElem.getUnqualifiedType();
7808 RHSElem = RHSElem.getUnqualifiedType();
7809 }
7810
7811 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007812 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007813 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7814 return LHS;
7815 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7816 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007817 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7818 ArrayType::ArraySizeModifier(), 0);
7819 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7820 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007821 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7822 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007823 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7824 return LHS;
7825 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7826 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007827 if (LVAT) {
7828 // FIXME: This isn't correct! But tricky to implement because
7829 // the array's size has to be the size of LHS, but the type
7830 // has to be different.
7831 return LHS;
7832 }
7833 if (RVAT) {
7834 // FIXME: This isn't correct! But tricky to implement because
7835 // the array's size has to be the size of RHS, but the type
7836 // has to be different.
7837 return RHS;
7838 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007839 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7840 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007841 return getIncompleteArrayType(ResultType,
7842 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007843 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007844 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007845 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007846 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007847 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007848 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007849 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007850 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007851 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007852 case Type::Complex:
7853 // Distinct complex types are incompatible.
7854 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007855 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007856 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007857 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7858 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007859 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007860 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007861 case Type::ObjCObject: {
7862 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007863 // FIXME: This should be type compatibility, e.g. whether
7864 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007865 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7866 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7867 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007868 return LHS;
7869
Eli Friedman47f77112008-08-22 00:56:42 +00007870 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007871 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007872 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007873 if (OfBlockPointer) {
7874 if (canAssignObjCInterfacesInBlockPointer(
7875 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007876 RHS->getAs<ObjCObjectPointerType>(),
7877 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007878 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007879 return QualType();
7880 }
John McCall9dd450b2009-09-21 23:43:11 +00007881 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7882 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007883 return LHS;
7884
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007885 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007886 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00007887 case Type::Pipe:
7888 {
7889 // Merge two pointer types, while trying to preserve typedef info
7890 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
7891 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
7892 if (Unqualified) {
7893 LHSValue = LHSValue.getUnqualifiedType();
7894 RHSValue = RHSValue.getUnqualifiedType();
7895 }
7896 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7897 Unqualified);
7898 if (ResultType.isNull()) return QualType();
7899 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7900 return LHS;
7901 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7902 return RHS;
7903 return getPipeType(ResultType);
7904 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007905 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007906
David Blaikie8a40f702012-01-17 06:56:22 +00007907 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007908}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007909
John McCall18afab72016-03-01 00:49:02 +00007910bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
7911 const FunctionProtoType *firstFnType,
7912 const FunctionProtoType *secondFnType) {
7913 // Fast path: if the first type doesn't have ext parameter infos,
7914 // we match if and only if they second type also doesn't have them.
7915 if (!firstFnType->hasExtParameterInfos())
7916 return !secondFnType->hasExtParameterInfos();
7917
7918 // Otherwise, we can only match if the second type has them.
7919 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007920 return false;
John McCall18afab72016-03-01 00:49:02 +00007921
7922 auto firstEPI = firstFnType->getExtParameterInfos();
7923 auto secondEPI = secondFnType->getExtParameterInfos();
7924 assert(firstEPI.size() == secondEPI.size());
7925
7926 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
7927 if (firstEPI[i] != secondEPI[i])
7928 return false;
7929 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007930 return true;
7931}
7932
Chandler Carruth21c90602015-12-30 03:24:14 +00007933void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
7934 ObjCLayouts[CD] = nullptr;
7935}
7936
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007937/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7938/// 'RHS' attributes and returns the merged version; including for function
7939/// return types.
7940QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7941 QualType LHSCan = getCanonicalType(LHS),
7942 RHSCan = getCanonicalType(RHS);
7943 // If two types are identical, they are compatible.
7944 if (LHSCan == RHSCan)
7945 return LHS;
7946 if (RHSCan->isFunctionType()) {
7947 if (!LHSCan->isFunctionType())
7948 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007949 QualType OldReturnType =
7950 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007951 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007952 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007953 QualType ResReturnType =
7954 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7955 if (ResReturnType.isNull())
7956 return QualType();
7957 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7958 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7959 // In either case, use OldReturnType to build the new function type.
7960 const FunctionType *F = LHS->getAs<FunctionType>();
7961 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007962 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7963 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007964 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007965 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007966 return ResultType;
7967 }
7968 }
7969 return QualType();
7970 }
7971
7972 // If the qualifiers are different, the types can still be merged.
7973 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7974 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7975 if (LQuals != RQuals) {
7976 // If any of these qualifiers are different, we have a type mismatch.
7977 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7978 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7979 return QualType();
7980
7981 // Exactly one GC qualifier difference is allowed: __strong is
7982 // okay if the other type has no GC qualifier but is an Objective
7983 // C object pointer (i.e. implicitly strong by default). We fix
7984 // this by pretending that the unqualified type was actually
7985 // qualified __strong.
7986 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7987 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7988 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7989
7990 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7991 return QualType();
7992
7993 if (GC_L == Qualifiers::Strong)
7994 return LHS;
7995 if (GC_R == Qualifiers::Strong)
7996 return RHS;
7997 return QualType();
7998 }
7999
8000 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8001 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8002 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8003 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8004 if (ResQT == LHSBaseQT)
8005 return LHS;
8006 if (ResQT == RHSBaseQT)
8007 return RHS;
8008 }
8009 return QualType();
8010}
8011
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008012//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008013// Integer Predicates
8014//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008015
Jay Foad39c79802011-01-12 09:06:06 +00008016unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008017 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008018 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008019 if (T->isBooleanType())
8020 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008021 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008022 return (unsigned)getTypeSize(T);
8023}
8024
Abramo Bagnara13640492012-09-09 10:21:24 +00008025QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008026 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008027
8028 // Turn <4 x signed int> -> <4 x unsigned int>
8029 if (const VectorType *VTy = T->getAs<VectorType>())
8030 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008031 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008032
8033 // For enums, we return the unsigned version of the base type.
8034 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008035 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008036
8037 const BuiltinType *BTy = T->getAs<BuiltinType>();
8038 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008039 switch (BTy->getKind()) {
8040 case BuiltinType::Char_S:
8041 case BuiltinType::SChar:
8042 return UnsignedCharTy;
8043 case BuiltinType::Short:
8044 return UnsignedShortTy;
8045 case BuiltinType::Int:
8046 return UnsignedIntTy;
8047 case BuiltinType::Long:
8048 return UnsignedLongTy;
8049 case BuiltinType::LongLong:
8050 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008051 case BuiltinType::Int128:
8052 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008053 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008054 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008055 }
8056}
8057
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008058ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008059
Richard Smith1fa5d642013-05-11 05:45:24 +00008060void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8061 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008062
8063//===----------------------------------------------------------------------===//
8064// Builtin Type Computation
8065//===----------------------------------------------------------------------===//
8066
8067/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008068/// pointer over the consumed characters. This returns the resultant type. If
8069/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8070/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8071/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008072///
8073/// RequiresICE is filled in on return to indicate whether the value is required
8074/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008075static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008076 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008077 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008078 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008079 // Modifiers.
8080 int HowLong = 0;
8081 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008082 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008083
Chris Lattnerdc226c22010-10-01 22:42:38 +00008084 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008085 bool Done = false;
8086 while (!Done) {
8087 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008088 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008089 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008090 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008091 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008092 case 'S':
8093 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8094 assert(!Signed && "Can't use 'S' modifier multiple times!");
8095 Signed = true;
8096 break;
8097 case 'U':
8098 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008099 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008100 Unsigned = true;
8101 break;
8102 case 'L':
8103 assert(HowLong <= 2 && "Can't have LLLL modifier");
8104 ++HowLong;
8105 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008106 case 'W':
8107 // This modifier represents int64 type.
8108 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8109 switch (Context.getTargetInfo().getInt64Type()) {
8110 default:
8111 llvm_unreachable("Unexpected integer type");
8112 case TargetInfo::SignedLong:
8113 HowLong = 1;
8114 break;
8115 case TargetInfo::SignedLongLong:
8116 HowLong = 2;
8117 break;
8118 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008119 }
8120 }
8121
8122 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008123
Chris Lattnerecd79c62009-06-14 00:45:47 +00008124 // Read the base type.
8125 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008126 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008127 case 'v':
8128 assert(HowLong == 0 && !Signed && !Unsigned &&
8129 "Bad modifiers used with 'v'!");
8130 Type = Context.VoidTy;
8131 break;
Jack Carter24bef982013-08-15 15:16:57 +00008132 case 'h':
8133 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008134 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008135 Type = Context.HalfTy;
8136 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008137 case 'f':
8138 assert(HowLong == 0 && !Signed && !Unsigned &&
8139 "Bad modifiers used with 'f'!");
8140 Type = Context.FloatTy;
8141 break;
8142 case 'd':
8143 assert(HowLong < 2 && !Signed && !Unsigned &&
8144 "Bad modifiers used with 'd'!");
8145 if (HowLong)
8146 Type = Context.LongDoubleTy;
8147 else
8148 Type = Context.DoubleTy;
8149 break;
8150 case 's':
8151 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8152 if (Unsigned)
8153 Type = Context.UnsignedShortTy;
8154 else
8155 Type = Context.ShortTy;
8156 break;
8157 case 'i':
8158 if (HowLong == 3)
8159 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8160 else if (HowLong == 2)
8161 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8162 else if (HowLong == 1)
8163 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8164 else
8165 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8166 break;
8167 case 'c':
8168 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8169 if (Signed)
8170 Type = Context.SignedCharTy;
8171 else if (Unsigned)
8172 Type = Context.UnsignedCharTy;
8173 else
8174 Type = Context.CharTy;
8175 break;
8176 case 'b': // boolean
8177 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8178 Type = Context.BoolTy;
8179 break;
8180 case 'z': // size_t.
8181 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8182 Type = Context.getSizeType();
8183 break;
8184 case 'F':
8185 Type = Context.getCFConstantStringType();
8186 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008187 case 'G':
8188 Type = Context.getObjCIdType();
8189 break;
8190 case 'H':
8191 Type = Context.getObjCSelType();
8192 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008193 case 'M':
8194 Type = Context.getObjCSuperType();
8195 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008196 case 'a':
8197 Type = Context.getBuiltinVaListType();
8198 assert(!Type.isNull() && "builtin va list type not initialized!");
8199 break;
8200 case 'A':
8201 // This is a "reference" to a va_list; however, what exactly
8202 // this means depends on how va_list is defined. There are two
8203 // different kinds of va_list: ones passed by value, and ones
8204 // passed by reference. An example of a by-value va_list is
8205 // x86, where va_list is a char*. An example of by-ref va_list
8206 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8207 // we want this argument to be a char*&; for x86-64, we want
8208 // it to be a __va_list_tag*.
8209 Type = Context.getBuiltinVaListType();
8210 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008211 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008212 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008213 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008214 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008215 break;
8216 case 'V': {
8217 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008218 unsigned NumElements = strtoul(Str, &End, 10);
8219 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008220 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008221
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008222 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8223 RequiresICE, false);
8224 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008225
8226 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008227 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008228 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008229 break;
8230 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008231 case 'E': {
8232 char *End;
8233
8234 unsigned NumElements = strtoul(Str, &End, 10);
8235 assert(End != Str && "Missing vector size");
8236
8237 Str = End;
8238
8239 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8240 false);
8241 Type = Context.getExtVectorType(ElementType, NumElements);
8242 break;
8243 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008244 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008245 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8246 false);
8247 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008248 Type = Context.getComplexType(ElementType);
8249 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008250 }
8251 case 'Y' : {
8252 Type = Context.getPointerDiffType();
8253 break;
8254 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008255 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008256 Type = Context.getFILEType();
8257 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008258 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008259 return QualType();
8260 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008261 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008262 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008263 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008264 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008265 else
8266 Type = Context.getjmp_bufType();
8267
Mike Stump2adb4da2009-07-28 23:47:15 +00008268 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008269 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008270 return QualType();
8271 }
8272 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008273 case 'K':
8274 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8275 Type = Context.getucontext_tType();
8276
8277 if (Type.isNull()) {
8278 Error = ASTContext::GE_Missing_ucontext;
8279 return QualType();
8280 }
8281 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008282 case 'p':
8283 Type = Context.getProcessIDType();
8284 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008285 }
Mike Stump11289f42009-09-09 15:08:12 +00008286
Chris Lattnerdc226c22010-10-01 22:42:38 +00008287 // If there are modifiers and if we're allowed to parse them, go for it.
8288 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008289 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008290 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008291 default: Done = true; --Str; break;
8292 case '*':
8293 case '&': {
8294 // Both pointers and references can have their pointee types
8295 // qualified with an address space.
8296 char *End;
8297 unsigned AddrSpace = strtoul(Str, &End, 10);
8298 if (End != Str && AddrSpace != 0) {
8299 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8300 Str = End;
8301 }
8302 if (c == '*')
8303 Type = Context.getPointerType(Type);
8304 else
8305 Type = Context.getLValueReferenceType(Type);
8306 break;
8307 }
8308 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8309 case 'C':
8310 Type = Type.withConst();
8311 break;
8312 case 'D':
8313 Type = Context.getVolatileType(Type);
8314 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008315 case 'R':
8316 Type = Type.withRestrict();
8317 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008318 }
8319 }
Chris Lattner84733392010-10-01 07:13:18 +00008320
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008321 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008322 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008323
Chris Lattnerecd79c62009-06-14 00:45:47 +00008324 return Type;
8325}
8326
8327/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008328QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008329 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008330 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008331 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008332
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008333 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008334
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008335 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008336 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008337 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8338 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008339 if (Error != GE_None)
8340 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008341
8342 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8343
Chris Lattnerecd79c62009-06-14 00:45:47 +00008344 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008345 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008346 if (Error != GE_None)
8347 return QualType();
8348
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008349 // If this argument is required to be an IntegerConstantExpression and the
8350 // caller cares, fill in the bitmask we return.
8351 if (RequiresICE && IntegerConstantArgs)
8352 *IntegerConstantArgs |= 1 << ArgTypes.size();
8353
Chris Lattnerecd79c62009-06-14 00:45:47 +00008354 // Do array -> pointer decay. The builtin should use the decayed type.
8355 if (Ty->isArrayType())
8356 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008357
Chris Lattnerecd79c62009-06-14 00:45:47 +00008358 ArgTypes.push_back(Ty);
8359 }
8360
David Majnemerba3e5ec2015-03-13 18:26:17 +00008361 if (Id == Builtin::BI__GetExceptionInfo)
8362 return QualType();
8363
Chris Lattnerecd79c62009-06-14 00:45:47 +00008364 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8365 "'.' should only occur at end of builtin type list!");
8366
Reid Kleckner78af0702013-08-27 23:08:25 +00008367 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008368 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8369
8370 bool Variadic = (TypeStr[0] == '.');
8371
8372 // We really shouldn't be making a no-proto type here, especially in C++.
8373 if (ArgTypes.empty() && Variadic)
8374 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008375
John McCalldb40c7f2010-12-14 08:05:40 +00008376 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008377 EPI.ExtInfo = EI;
8378 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008379
Jordan Rose5c382722013-03-08 21:51:21 +00008380 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008381}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008382
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008383static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8384 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008385 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008386 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008387
Rafael Espindola3ae00052013-05-13 00:12:11 +00008388 GVALinkage External = GVA_StrongExternal;
8389 switch (FD->getTemplateSpecializationKind()) {
8390 case TSK_Undeclared:
8391 case TSK_ExplicitSpecialization:
8392 External = GVA_StrongExternal;
8393 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008394
Rafael Espindola3ae00052013-05-13 00:12:11 +00008395 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008396 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008397
David Majnemerc3d07332014-05-15 06:25:57 +00008398 // C++11 [temp.explicit]p10:
8399 // [ Note: The intent is that an inline function that is the subject of
8400 // an explicit instantiation declaration will still be implicitly
8401 // instantiated when used so that the body can be considered for
8402 // inlining, but that no out-of-line copy of the inline function would be
8403 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008404 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008405 return GVA_AvailableExternally;
8406
Rafael Espindola3ae00052013-05-13 00:12:11 +00008407 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008408 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008409 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008410 }
8411
8412 if (!FD->isInlined())
8413 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008414
David Majnemer3f021502015-10-08 04:53:31 +00008415 if ((!Context.getLangOpts().CPlusPlus &&
8416 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008417 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008418 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008419 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8420
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008421 // GNU or C99 inline semantics. Determine whether this symbol should be
8422 // externally visible.
8423 if (FD->isInlineDefinitionExternallyVisible())
8424 return External;
8425
8426 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008427 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008428 }
8429
David Majnemer54e3ba52014-04-02 23:17:29 +00008430 // Functions specified with extern and inline in -fms-compatibility mode
8431 // forcibly get emitted. While the body of the function cannot be later
8432 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008433 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008434 return GVA_StrongODR;
8435
David Majnemer27d69db2014-04-28 22:17:59 +00008436 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008437}
8438
Artem Belevich7b41f702015-09-23 17:44:53 +00008439static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008440 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8441 // dllexport/dllimport on inline functions.
8442 if (D->hasAttr<DLLImportAttr>()) {
8443 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8444 return GVA_AvailableExternally;
Artem Belevich7b41f702015-09-23 17:44:53 +00008445 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008446 if (L == GVA_DiscardableODR)
8447 return GVA_StrongODR;
8448 }
8449 return L;
8450}
8451
8452GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevich7b41f702015-09-23 17:44:53 +00008453 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8454 FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008455}
8456
8457static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8458 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008459 if (!VD->isExternallyVisible())
8460 return GVA_Internal;
8461
David Majnemer27d69db2014-04-28 22:17:59 +00008462 if (VD->isStaticLocal()) {
8463 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8464 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8465 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8466 LexicalContext = LexicalContext->getLexicalParent();
8467
Richard Smith9e2341d2015-03-23 03:25:59 +00008468 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008469 // enclosing function.
8470 if (LexicalContext)
8471 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008472 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008473
8474 // GVA_StrongODR function linkage is stronger than what we need,
8475 // downgrade to GVA_DiscardableODR.
8476 // This allows us to discard the variable if we never end up needing it.
8477 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8478 : StaticLocalLinkage;
8479 }
8480
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008481 // MSVC treats in-class initialized static data members as definitions.
8482 // By giving them non-strong linkage, out-of-line definitions won't
8483 // cause link errors.
8484 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8485 return GVA_DiscardableODR;
8486
Richard Smith8809a0c2013-09-27 20:14:12 +00008487 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008488 case TSK_Undeclared:
Rafael Espindola3ae00052013-05-13 00:12:11 +00008489 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008490
David Majnemer6d1780c2015-07-17 23:36:49 +00008491 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008492 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8493 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008494 ? GVA_StrongODR
8495 : GVA_StrongExternal;
8496
Rafael Espindola3ae00052013-05-13 00:12:11 +00008497 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008498 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008499
David Majnemer27d69db2014-04-28 22:17:59 +00008500 case TSK_ExplicitInstantiationDeclaration:
8501 return GVA_AvailableExternally;
8502
Rafael Espindola3ae00052013-05-13 00:12:11 +00008503 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008504 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008505 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008506
8507 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008508}
8509
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008510GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevich7b41f702015-09-23 17:44:53 +00008511 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8512 VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008513}
8514
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008515bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008516 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8517 if (!VD->isFileVarDecl())
8518 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008519 // Global named register variables (GNU extension) are never emitted.
8520 if (VD->getStorageClass() == SC_Register)
8521 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008522 if (VD->getDescribedVarTemplate() ||
8523 isa<VarTemplatePartialSpecializationDecl>(VD))
8524 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008525 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8526 // We never need to emit an uninstantiated function template.
8527 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8528 return false;
Nico Weber66220292016-03-02 17:28:48 +00008529 } else if (isa<PragmaCommentDecl>(D))
8530 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008531 else if (isa<PragmaDetectMismatchDecl>(D))
8532 return true;
Nico Weber66220292016-03-02 17:28:48 +00008533 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008534 return !D->getDeclContext()->isDependentContext();
8535 else if (isa<OMPDeclareReductionDecl>(D))
8536 return !D->getDeclContext()->isDependentContext();
Alexey Bataev97720002014-11-11 04:05:39 +00008537 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008538 return false;
8539
8540 // If this is a member of a class template, we do not need to emit it.
8541 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008542 return false;
8543
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008544 // Weak references don't produce any output by themselves.
8545 if (D->hasAttr<WeakRefAttr>())
8546 return false;
8547
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008548 // Aliases and used decls are required.
8549 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8550 return true;
8551
8552 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8553 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008554 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008555 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008556
8557 // Constructors and destructors are required.
8558 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8559 return true;
8560
John McCall6bd2a892013-01-25 22:31:03 +00008561 // The key function for a class is required. This rule only comes
8562 // into play when inline functions can be key functions, though.
8563 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8564 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8565 const CXXRecordDecl *RD = MD->getParent();
8566 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8567 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8568 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8569 return true;
8570 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008571 }
8572 }
8573
8574 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8575
8576 // static, static inline, always_inline, and extern inline functions can
8577 // always be deferred. Normal inline functions can be deferred in C99/C++.
8578 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008579 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8580 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008581 return false;
8582 return true;
8583 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008584
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008585 const VarDecl *VD = cast<VarDecl>(D);
8586 assert(VD->isFileVarDecl() && "Expected file scoped var");
8587
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008588 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8589 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008590 return false;
8591
Richard Smitha0e5e542012-11-12 21:38:00 +00008592 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008593 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008594 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8595 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008596 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008597
Richard Smitha0e5e542012-11-12 21:38:00 +00008598 // Variables that have destruction with side-effects are required.
8599 if (VD->getType().isDestructedType())
8600 return true;
8601
8602 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008603 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8604 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008605 return true;
8606
8607 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008608}
Charles Davis53c59df2010-08-16 03:33:14 +00008609
Reid Kleckner78af0702013-08-27 23:08:25 +00008610CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8611 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008612 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008613 if (IsCXXMethod)
8614 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008615
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008616 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8617
8618 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008619}
8620
Jay Foad39c79802011-01-12 09:06:06 +00008621bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008622 // Pass through to the C++ ABI object
8623 return ABI->isNearlyEmpty(RD);
8624}
8625
Reid Kleckner96f8f932014-02-05 17:27:08 +00008626VTableContextBase *ASTContext::getVTableContext() {
8627 if (!VTContext.get()) {
8628 if (Target->getCXXABI().isMicrosoft())
8629 VTContext.reset(new MicrosoftVTableContext(*this));
8630 else
8631 VTContext.reset(new ItaniumVTableContext(*this));
8632 }
8633 return VTContext.get();
8634}
8635
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008636MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008637 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008638 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008639 case TargetCXXABI::GenericItanium:
8640 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008641 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008642 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008643 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008644 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008645 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008646 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008647 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008648 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008649 }
David Blaikie83d382b2011-09-23 05:06:16 +00008650 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008651}
8652
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008653CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008654
8655size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008656 return ASTRecordLayouts.getMemorySize() +
8657 llvm::capacity_in_bytes(ObjCLayouts) +
8658 llvm::capacity_in_bytes(KeyFunctions) +
8659 llvm::capacity_in_bytes(ObjCImpls) +
8660 llvm::capacity_in_bytes(BlockVarCopyInits) +
8661 llvm::capacity_in_bytes(DeclAttrs) +
8662 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8663 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8664 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8665 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8666 llvm::capacity_in_bytes(OverriddenMethods) +
8667 llvm::capacity_in_bytes(Types) +
8668 llvm::capacity_in_bytes(VariableArrayTypes) +
8669 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008670}
Ted Kremenek540017e2011-10-06 05:00:56 +00008671
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008672/// getIntTypeForBitwidth -
8673/// sets integer QualTy according to specified details:
8674/// bitwidth, signed/unsigned.
8675/// Returns empty type if there is no appropriate target types.
8676QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8677 unsigned Signed) const {
8678 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8679 CanQualType QualTy = getFromTargetType(Ty);
8680 if (!QualTy && DestWidth == 128)
8681 return Signed ? Int128Ty : UnsignedInt128Ty;
8682 return QualTy;
8683}
8684
8685/// getRealTypeForBitwidth -
8686/// sets floating point QualTy according to specified bitwidth.
8687/// Returns empty type if there is no appropriate target types.
8688QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8689 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8690 switch (Ty) {
8691 case TargetInfo::Float:
8692 return FloatTy;
8693 case TargetInfo::Double:
8694 return DoubleTy;
8695 case TargetInfo::LongDouble:
8696 return LongDoubleTy;
8697 case TargetInfo::NoFloat:
8698 return QualType();
8699 }
8700
8701 llvm_unreachable("Unhandled TargetInfo::RealType value");
8702}
8703
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008704void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8705 if (Number > 1)
8706 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008707}
8708
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008709unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008710 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008711 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008712}
8713
David Majnemer2206bf52014-03-05 08:57:59 +00008714void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8715 if (Number > 1)
8716 StaticLocalNumbers[VD] = Number;
8717}
8718
8719unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008720 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00008721 return I != StaticLocalNumbers.end() ? I->second : 1;
8722}
8723
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008724MangleNumberingContext &
8725ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008726 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8727 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8728 if (!MCtx)
8729 MCtx = createMangleNumberingContext();
8730 return *MCtx;
8731}
8732
8733MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8734 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008735}
8736
David Majnemere7a818f2015-03-06 18:53:55 +00008737const CXXConstructorDecl *
8738ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8739 return ABI->getCopyConstructorForExceptionObject(
8740 cast<CXXRecordDecl>(RD->getFirstDecl()));
8741}
8742
8743void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8744 CXXConstructorDecl *CD) {
8745 return ABI->addCopyConstructorForExceptionObject(
8746 cast<CXXRecordDecl>(RD->getFirstDecl()),
8747 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8748}
8749
David Majnemerdfa6d202015-03-11 18:36:39 +00008750void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8751 unsigned ParmIdx, Expr *DAE) {
8752 ABI->addDefaultArgExprForConstructor(
8753 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8754}
8755
8756Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8757 unsigned ParmIdx) {
8758 return ABI->getDefaultArgExprForConstructor(
8759 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8760}
8761
David Majnemer00350522015-08-31 18:48:39 +00008762void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8763 TypedefNameDecl *DD) {
8764 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8765}
8766
8767TypedefNameDecl *
8768ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8769 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8770}
8771
8772void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8773 DeclaratorDecl *DD) {
8774 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8775}
8776
8777DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8778 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8779}
8780
Ted Kremenek540017e2011-10-06 05:00:56 +00008781void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8782 ParamIndices[D] = index;
8783}
8784
8785unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8786 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8787 assert(I != ParamIndices.end() &&
8788 "ParmIndices lacks entry set by ParmVarDecl");
8789 return I->second;
8790}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008791
Richard Smithe6c01442013-06-05 00:46:14 +00008792APValue *
8793ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8794 bool MayCreate) {
8795 assert(E && E->getStorageDuration() == SD_Static &&
8796 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008797 if (MayCreate) {
8798 APValue *&MTVI = MaterializedTemporaryValues[E];
8799 if (!MTVI)
8800 MTVI = new (*this) APValue;
8801 return MTVI;
8802 }
Richard Smithe6c01442013-06-05 00:46:14 +00008803
David Majnemer2dcef9e2015-08-13 23:50:15 +00008804 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008805}
8806
Fariborz Jahanian615de762013-05-28 17:37:39 +00008807bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8808 const llvm::Triple &T = getTargetInfo().getTriple();
8809 if (!T.isOSDarwin())
8810 return false;
8811
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008812 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8813 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8814 return false;
8815
Fariborz Jahanian615de762013-05-28 17:37:39 +00008816 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8817 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8818 uint64_t Size = sizeChars.getQuantity();
8819 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8820 unsigned Align = alignChars.getQuantity();
8821 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8822 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8823}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008824
8825namespace {
8826
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008827ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8828 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008829 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008830 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008831 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008832 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008833 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008834}
8835
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008836/// Template specializations to abstract away from pointers and TypeLocs.
8837/// @{
8838template <typename T>
8839ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8840 return ast_type_traits::DynTypedNode::create(*Node);
8841}
8842template <>
8843ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8844 return ast_type_traits::DynTypedNode::create(Node);
8845}
8846template <>
8847ast_type_traits::DynTypedNode
8848createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8849 return ast_type_traits::DynTypedNode::create(Node);
8850}
8851/// @}
8852
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008853 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8854 /// parents as defined by the \c RecursiveASTVisitor.
8855 ///
8856 /// Note that the relationship described here is purely in terms of AST
8857 /// traversal - there are other relationships (for example declaration context)
8858 /// in the AST that are better modeled by special matchers.
8859 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008860 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008861 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008862 public:
8863 /// \brief Builds and returns the translation unit's parent map.
8864 ///
8865 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008866 static std::pair<ASTContext::ParentMapPointers *,
8867 ASTContext::ParentMapOtherNodes *>
8868 buildMap(TranslationUnitDecl &TU) {
8869 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8870 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008871 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008872 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008873 }
8874
8875 private:
8876 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8877
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008878 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8879 ASTContext::ParentMapOtherNodes *OtherParents)
8880 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008881
8882 bool shouldVisitTemplateInstantiations() const {
8883 return true;
8884 }
8885 bool shouldVisitImplicitCode() const {
8886 return true;
8887 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008888
Richard Smith85838722015-11-24 03:09:01 +00008889 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8890 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008891 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00008892 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00008893 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008894 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008895 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008896 // FIXME: Currently we add the same parent multiple times, but only
8897 // when no memoization data is available for the type.
8898 // For example when we visit all subexpressions of template
8899 // instantiations; this is suboptimal, but benign: the only way to
8900 // visit those is with hasAncestor / hasParent, and those do not create
8901 // new matches.
8902 // The plan is to enable DynTypedNode to be storable in a map or hash
8903 // map. The main problem there is to implement hash functions /
8904 // comparison operators for all types that DynTypedNode supports that
8905 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008906 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00008907 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008908 if (const auto *D = ParentStack.back().get<Decl>())
8909 NodeOrVector = D;
8910 else if (const auto *S = ParentStack.back().get<Stmt>())
8911 NodeOrVector = S;
8912 else
8913 NodeOrVector =
8914 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008915 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008916 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8917 auto *Vector = new ASTContext::ParentVector(
8918 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008919 if (auto *Node =
8920 NodeOrVector
8921 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8922 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00008923 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008924 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008925
8926 auto *Vector =
8927 NodeOrVector.template get<ASTContext::ParentVector *>();
8928 // Skip duplicates for types that have memoization data.
8929 // We must check that the type has memoization data before calling
8930 // std::find() because DynTypedNode::operator== can't compare all
8931 // types.
8932 bool Found = ParentStack.back().getMemoizationData() &&
8933 std::find(Vector->begin(), Vector->end(),
8934 ParentStack.back()) != Vector->end();
8935 if (!Found)
8936 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008937 }
8938 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008939 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00008940 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008941 ParentStack.pop_back();
8942 return Result;
8943 }
8944
8945 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00008946 return TraverseNode(DeclNode, DeclNode,
8947 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008948 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008949 }
8950
8951 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00008952 return TraverseNode(StmtNode, StmtNode,
8953 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008954 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008955 }
8956
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008957 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00008958 return TraverseNode(
8959 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
8960 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
8961 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008962 }
8963
8964 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
8965 return TraverseNode(
8966 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00008967 [&] {
8968 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
8969 },
8970 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008971 }
8972
8973 ASTContext::ParentMapPointers *Parents;
8974 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008975 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8976
8977 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8978 };
8979
Eugene Zelenkod4304d22015-11-04 21:37:17 +00008980} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008981
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008982template <typename NodeTy, typename MapTy>
8983static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
8984 const MapTy &Map) {
8985 auto I = Map.find(Node);
8986 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008987 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008988 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008989 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008990 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00008991 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008992 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008993}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008994
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008995ASTContext::DynTypedNodeList
8996ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8997 if (!PointerParents) {
8998 // We always need to run over the whole translation unit, as
8999 // hasAncestor can escape any subtree.
9000 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9001 PointerParents.reset(Maps.first);
9002 OtherParents.reset(Maps.second);
9003 }
9004 if (Node.getNodeKind().hasPointerIdentity())
9005 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9006 return getDynNodeFromMap(Node, *OtherParents);
9007}
9008
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009009bool
9010ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9011 const ObjCMethodDecl *MethodImpl) {
9012 // No point trying to match an unavailable/deprecated mothod.
9013 if (MethodDecl->hasAttr<UnavailableAttr>()
9014 || MethodDecl->hasAttr<DeprecatedAttr>())
9015 return false;
9016 if (MethodDecl->getObjCDeclQualifier() !=
9017 MethodImpl->getObjCDeclQualifier())
9018 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009019 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009020 return false;
9021
9022 if (MethodDecl->param_size() != MethodImpl->param_size())
9023 return false;
9024
9025 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9026 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9027 EF = MethodDecl->param_end();
9028 IM != EM && IF != EF; ++IM, ++IF) {
9029 const ParmVarDecl *DeclVar = (*IF);
9030 const ParmVarDecl *ImplVar = (*IM);
9031 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9032 return false;
9033 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9034 return false;
9035 }
9036 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9037
9038}
Richard Smith053f6c62014-05-16 23:01:30 +00009039
9040// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9041// doesn't include ASTContext.h
9042template
9043clang::LazyGenerationalUpdatePtr<
9044 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9045clang::LazyGenerationalUpdatePtr<
9046 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9047 const clang::ASTContext &Ctx, Decl *Value);