blob: 22831f45d4afe149e4fbd7290c4c3be6d12aa457 [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 {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000061 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
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,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000636 ExpandedTypes,
637 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000638 } else {
639 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000640 SourceLocation(),
641 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000642 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000643 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000644 T,
645 NTTP->isParameterPack(),
646 TInfo);
647 }
648 CanonParams.push_back(Param);
649
650 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000651 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
652 cast<TemplateTemplateParmDecl>(*P)));
653 }
654
655 TemplateTemplateParmDecl *CanonTTP
656 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
657 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000658 TTP->getPosition(),
659 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000660 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000661 TemplateParameterList::Create(*this, SourceLocation(),
662 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000663 CanonParams,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664 SourceLocation()));
665
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000668 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 (void)Canonical;
670
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674 return CanonTTP;
675}
676
Charles Davis53c59df2010-08-16 03:33:14 +0000677CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000678 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000679
John McCall359b8852013-01-25 22:30:49 +0000680 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000682 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000683 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000684 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000685 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000686 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000687 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000688 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000689 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000690 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000691 return CreateMicrosoftCXXABI(*this);
692 }
David Blaikie8a40f702012-01-17 06:56:22 +0000693 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000694}
695
Douglas Gregore8bbc122011-09-02 00:18:52 +0000696static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000697 const LangOptions &LOpts) {
698 if (LOpts.FakeAddressSpaceMap) {
699 // The fake address space map must have a distinct entry for each
700 // language-specific address space.
701 static const unsigned FakeAddrSpaceMap[] = {
702 1, // opencl_global
703 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000704 3, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000705 4, // opencl_generic
706 5, // cuda_device
707 6, // cuda_constant
708 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000709 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000711 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000712 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000713 }
714}
715
David Tweed31d09b02013-09-13 12:04:22 +0000716static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
717 const LangOptions &LangOpts) {
718 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000719 case LangOptions::ASMM_Target:
720 return TI.useAddressSpaceMapMangling();
721 case LangOptions::ASMM_On:
722 return true;
723 case LangOptions::ASMM_Off:
724 return false;
725 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000726 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000727}
728
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000729ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000730 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000731 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000732 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
733 DependentTemplateSpecializationTypes(this_()),
734 SubstTemplateTemplateParmPacks(this_()),
735 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000736 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
737 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
738 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000739 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
740 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
741 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
742 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
743 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000744 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
745 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000746 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000747 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
748 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
749 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
750 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000751 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000752 TUDecl = TranslationUnitDecl::Create(*this);
753}
754
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000755ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000756 ReleaseParentMapEntries();
757
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000758 // Release the DenseMaps associated with DeclContext objects.
759 // FIXME: Is this the ideal solution?
760 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000761
Manuel Klimeka7328992013-06-03 13:51:33 +0000762 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000763 for (auto &Pair : Deallocations)
764 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000765
Ted Kremenek076baeb2010-06-08 23:00:58 +0000766 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000767 // because they can contain DenseMaps.
768 for (llvm::DenseMap<const ObjCContainerDecl*,
769 const ASTRecordLayout*>::iterator
770 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
771 // Increment in loop to prevent using deallocated memory.
772 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
773 R->Destroy(*this);
774
Ted Kremenek076baeb2010-06-08 23:00:58 +0000775 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
776 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
777 // Increment in loop to prevent using deallocated memory.
778 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
779 R->Destroy(*this);
780 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000781
782 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
783 AEnd = DeclAttrs.end();
784 A != AEnd; ++A)
785 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000786
David Majnemere694f3e2015-08-14 14:43:50 +0000787 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
788 MaterializedTemporaryValues)
789 MTVPair.second->~APValue();
790
Reid Kleckner588c9372014-02-19 23:44:52 +0000791 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000792}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000793
Manuel Klimek95403e62014-05-21 13:28:59 +0000794void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000795 if (!PointerParents) return;
796 for (const auto &Entry : *PointerParents) {
797 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
798 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
799 } else if (Entry.second.is<ParentVector *>()) {
800 delete Entry.second.get<ParentVector *>();
801 }
802 }
803 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000804 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
805 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000806 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000807 delete Entry.second.get<ParentVector *>();
808 }
809 }
810}
811
Douglas Gregor1a809332010-05-23 18:26:36 +0000812void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000813 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000814}
815
Mike Stump11289f42009-09-09 15:08:12 +0000816void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000817ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000818 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000819}
820
Chris Lattner4eb445d2007-01-26 01:27:23 +0000821void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000822 llvm::errs() << "\n*** AST Context Stats:\n";
823 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000824
Douglas Gregora30d0462009-05-26 14:40:08 +0000825 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000826#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000827#define ABSTRACT_TYPE(Name, Parent)
828#include "clang/AST/TypeNodes.def"
829 0 // Extra
830 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000831
Chris Lattner4eb445d2007-01-26 01:27:23 +0000832 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
833 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000834 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000835 }
836
Douglas Gregora30d0462009-05-26 14:40:08 +0000837 unsigned Idx = 0;
838 unsigned TotalBytes = 0;
839#define TYPE(Name, Parent) \
840 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000841 llvm::errs() << " " << counts[Idx] << " " << #Name \
842 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000843 TotalBytes += counts[Idx] * sizeof(Name##Type); \
844 ++Idx;
845#define ABSTRACT_TYPE(Name, Parent)
846#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chandler Carruth3c147a72011-07-04 05:32:14 +0000848 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
849
Douglas Gregor7454c562010-07-02 20:37:36 +0000850 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000851 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
852 << NumImplicitDefaultConstructors
853 << " implicit default constructors created\n";
854 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
855 << NumImplicitCopyConstructors
856 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000857 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000858 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
859 << NumImplicitMoveConstructors
860 << " implicit move constructors created\n";
861 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
862 << NumImplicitCopyAssignmentOperators
863 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000864 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000865 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
866 << NumImplicitMoveAssignmentOperators
867 << " implicit move assignment operators created\n";
868 llvm::errs() << NumImplicitDestructorsDeclared << "/"
869 << NumImplicitDestructors
870 << " implicit destructors created\n";
871
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000872 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000873 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000874 ExternalSource->PrintStats();
875 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000876
Douglas Gregor5b11d492010-07-25 17:53:33 +0000877 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000878}
879
Richard Smith42413142015-05-15 20:05:43 +0000880void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
881 bool NotifyListeners) {
882 if (NotifyListeners)
883 if (auto *Listener = getASTMutationListener())
884 Listener->RedefinedHiddenDefinition(ND, M);
885
886 if (getLangOpts().ModulesLocalVisibility)
887 MergedDefModules[ND].push_back(M);
888 else
889 ND->setHidden(false);
890}
891
892void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
893 auto It = MergedDefModules.find(ND);
894 if (It == MergedDefModules.end())
895 return;
896
897 auto &Merged = It->second;
898 llvm::DenseSet<Module*> Found;
899 for (Module *&M : Merged)
900 if (!Found.insert(M).second)
901 M = nullptr;
902 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
903}
904
Richard Smithf19e1272015-03-07 00:04:49 +0000905ExternCContextDecl *ASTContext::getExternCContextDecl() const {
906 if (!ExternCContext)
907 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
908
909 return ExternCContext;
910}
911
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000912BuiltinTemplateDecl *
913ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
914 const IdentifierInfo *II) const {
915 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
916 BuiltinTemplate->setImplicit();
917 TUDecl->addDecl(BuiltinTemplate);
918
919 return BuiltinTemplate;
920}
921
922BuiltinTemplateDecl *
923ASTContext::getMakeIntegerSeqDecl() const {
924 if (!MakeIntegerSeqDecl)
925 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
926 getMakeIntegerSeqName());
927 return MakeIntegerSeqDecl;
928}
929
Eric Fiselier6ad68552016-07-01 01:24:09 +0000930BuiltinTemplateDecl *
931ASTContext::getTypePackElementDecl() const {
932 if (!TypePackElementDecl)
933 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
934 getTypePackElementName());
935 return TypePackElementDecl;
936}
937
Alp Toker2dea15b2013-12-17 01:22:38 +0000938RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
939 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000940 SourceLocation Loc;
941 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000942 if (getLangOpts().CPlusPlus)
943 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
944 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000945 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000946 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
947 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000948 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +0000949 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
950 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +0000951 return NewDecl;
952}
953
954TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
955 StringRef Name) const {
956 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
957 TypedefDecl *NewDecl = TypedefDecl::Create(
958 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
959 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
960 NewDecl->setImplicit();
961 return NewDecl;
962}
963
Douglas Gregor801c99d2011-08-12 06:49:56 +0000964TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000965 if (!Int128Decl)
966 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000967 return Int128Decl;
968}
969
970TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000971 if (!UInt128Decl)
972 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000973 return UInt128Decl;
974}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000975
John McCall48f2d582009-10-23 23:03:21 +0000976void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000977 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000978 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000979 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000980}
981
Artem Belevichb5bc9232015-09-22 17:23:22 +0000982void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
983 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000984 assert((!this->Target || this->Target == &Target) &&
985 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000986 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000987
Douglas Gregore8bbc122011-09-02 00:18:52 +0000988 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000989 this->AuxTarget = AuxTarget;
990
Douglas Gregore8bbc122011-09-02 00:18:52 +0000991 ABI.reset(createCXXABI(Target));
992 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000993 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000994
Chris Lattner970e54e2006-11-12 00:37:36 +0000995 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000996 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000997
Chris Lattner970e54e2006-11-12 00:37:36 +0000998 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000999 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001000 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001001 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001002 InitBuiltinType(CharTy, BuiltinType::Char_S);
1003 else
1004 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001005 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001006 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1007 InitBuiltinType(ShortTy, BuiltinType::Short);
1008 InitBuiltinType(IntTy, BuiltinType::Int);
1009 InitBuiltinType(LongTy, BuiltinType::Long);
1010 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattner970e54e2006-11-12 00:37:36 +00001012 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001013 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1014 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1015 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1016 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1017 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001018
Chris Lattner970e54e2006-11-12 00:37:36 +00001019 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001020 InitBuiltinType(FloatTy, BuiltinType::Float);
1021 InitBuiltinType(DoubleTy, BuiltinType::Double);
1022 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001023
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001024 // GNU extension, __float128 for IEEE quadruple precision
1025 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1026
Chris Lattnerf122cef2009-04-30 02:43:43 +00001027 // GNU extension, 128-bit integers.
1028 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1029 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1030
Hans Wennborg0d81e012013-05-10 10:08:40 +00001031 // C++ 3.9.1p5
1032 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1033 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1034 else // -fshort-wchar makes wchar_t be unsigned.
1035 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1036 if (LangOpts.CPlusPlus && LangOpts.WChar)
1037 WideCharTy = WCharTy;
1038 else {
1039 // C99 (or C++ using -fno-wchar).
1040 WideCharTy = getFromTargetType(Target.getWCharType());
1041 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001042
James Molloy36365542012-05-04 10:55:22 +00001043 WIntTy = getFromTargetType(Target.getWIntType());
1044
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001045 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1046 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1047 else // C99
1048 Char16Ty = getFromTargetType(Target.getChar16Type());
1049
1050 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1051 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1052 else // C99
1053 Char32Ty = getFromTargetType(Target.getChar32Type());
1054
Douglas Gregor4619e432008-12-05 23:32:09 +00001055 // Placeholder type for type-dependent expressions whose type is
1056 // completely unknown. No code should ever check a type against
1057 // DependentTy and users should never see it; however, it is here to
1058 // help diagnose failures to properly check for type-dependent
1059 // expressions.
1060 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061
John McCall36e7fe32010-10-12 00:20:44 +00001062 // Placeholder type for functions.
1063 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1064
John McCall0009fcc2011-04-26 20:42:42 +00001065 // Placeholder type for bound members.
1066 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1067
John McCall526ab472011-10-25 17:37:35 +00001068 // Placeholder type for pseudo-objects.
1069 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1070
John McCall31996342011-04-07 08:22:57 +00001071 // "any" type; useful for debugger-like clients.
1072 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1073
John McCall8a6b59a2011-10-17 18:09:15 +00001074 // Placeholder type for unbridged ARC casts.
1075 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1076
Eli Friedman34866c72012-08-31 00:14:07 +00001077 // Placeholder type for builtin functions.
1078 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1079
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001080 // Placeholder type for OMP array sections.
1081 if (LangOpts.OpenMP)
1082 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1083
Chris Lattner970e54e2006-11-12 00:37:36 +00001084 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001085 FloatComplexTy = getComplexType(FloatTy);
1086 DoubleComplexTy = getComplexType(DoubleTy);
1087 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001088 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001089
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001090 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001091 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1092 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001093 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001094
Alexey Bader954ba212016-04-08 13:40:33 +00001095 if (LangOpts.OpenCL) {
1096#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1097 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001098#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001099
Guy Benyei61054192013-02-07 10:55:47 +00001100 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001101 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001102 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1103 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1104 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1105 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001106 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001107
1108 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001109 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1110 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001111
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001112 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001113
1114 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001115
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001116 // void * type
1117 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001118
1119 // nullptr type (C++0x 2.14.7)
1120 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001121
1122 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1123 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001124
1125 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001126 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001127}
1128
David Blaikie9c902b52011-09-25 23:23:43 +00001129DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001130 return SourceMgr.getDiagnostics();
1131}
1132
Douglas Gregor561eceb2010-08-30 16:49:28 +00001133AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1134 AttrVec *&Result = DeclAttrs[D];
1135 if (!Result) {
1136 void *Mem = Allocate(sizeof(AttrVec));
1137 Result = new (Mem) AttrVec;
1138 }
1139
1140 return *Result;
1141}
1142
1143/// \brief Erase the attributes corresponding to the given declaration.
1144void ASTContext::eraseDeclAttrs(const Decl *D) {
1145 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1146 if (Pos != DeclAttrs.end()) {
1147 Pos->second->~AttrVec();
1148 DeclAttrs.erase(Pos);
1149 }
1150}
1151
Larisse Voufo39a1e502013-08-06 01:03:05 +00001152// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001153MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001154ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001155 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001156 return getTemplateOrSpecializationInfo(Var)
1157 .dyn_cast<MemberSpecializationInfo *>();
1158}
1159
1160ASTContext::TemplateOrSpecializationInfo
1161ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1162 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1163 TemplateOrInstantiation.find(Var);
1164 if (Pos == TemplateOrInstantiation.end())
1165 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001166
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001167 return Pos->second;
1168}
1169
Mike Stump11289f42009-09-09 15:08:12 +00001170void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001171ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001172 TemplateSpecializationKind TSK,
1173 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001174 assert(Inst->isStaticDataMember() && "Not a static data member");
1175 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001176 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1177 Tmpl, TSK, PointOfInstantiation));
1178}
1179
1180void
1181ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1182 TemplateOrSpecializationInfo TSI) {
1183 assert(!TemplateOrInstantiation[Inst] &&
1184 "Already noted what the variable was instantiated from");
1185 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001186}
1187
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001188FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1189 const FunctionDecl *FD){
1190 assert(FD && "Specialization is 0");
1191 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001192 = ClassScopeSpecializationPattern.find(FD);
1193 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001194 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001195
1196 return Pos->second;
1197}
1198
1199void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1200 FunctionDecl *Pattern) {
1201 assert(FD && "Specialization is 0");
1202 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001203 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001204}
1205
John McCalle61f2ba2009-11-18 02:36:19 +00001206NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001207ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001208 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001209 = InstantiatedFromUsingDecl.find(UUD);
1210 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001211 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001212
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001213 return Pos->second;
1214}
1215
1216void
John McCallb96ec562009-12-04 22:46:56 +00001217ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1218 assert((isa<UsingDecl>(Pattern) ||
1219 isa<UnresolvedUsingValueDecl>(Pattern) ||
1220 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1221 "pattern decl is not a using decl");
1222 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1223 InstantiatedFromUsingDecl[Inst] = Pattern;
1224}
1225
1226UsingShadowDecl *
1227ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1228 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1229 = InstantiatedFromUsingShadowDecl.find(Inst);
1230 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001231 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001232
1233 return Pos->second;
1234}
1235
1236void
1237ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1238 UsingShadowDecl *Pattern) {
1239 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1240 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001241}
1242
Anders Carlsson5da84842009-09-01 04:26:58 +00001243FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1244 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1245 = InstantiatedFromUnnamedFieldDecl.find(Field);
1246 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001247 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001248
Anders Carlsson5da84842009-09-01 04:26:58 +00001249 return Pos->second;
1250}
1251
1252void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1253 FieldDecl *Tmpl) {
1254 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1255 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1256 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1257 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001258
Anders Carlsson5da84842009-09-01 04:26:58 +00001259 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1260}
1261
Douglas Gregor832940b2010-03-02 23:58:15 +00001262ASTContext::overridden_cxx_method_iterator
1263ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001264 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1265 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001266 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001267 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001268 return Pos->second.begin();
1269}
1270
1271ASTContext::overridden_cxx_method_iterator
1272ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001273 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1274 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001275 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001276 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001277 return Pos->second.end();
1278}
1279
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001280unsigned
1281ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001282 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1283 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001284 if (Pos == OverriddenMethods.end())
1285 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001286 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001287}
1288
Clement Courbet6ecaec82016-07-05 07:49:31 +00001289ASTContext::overridden_method_range
1290ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1291 return overridden_method_range(overridden_methods_begin(Method),
1292 overridden_methods_end(Method));
1293}
1294
Douglas Gregor832940b2010-03-02 23:58:15 +00001295void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1296 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001297 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001298 OverriddenMethods[Method].push_back(Overridden);
1299}
1300
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001301void ASTContext::getOverriddenMethods(
1302 const NamedDecl *D,
1303 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001304 assert(D);
1305
1306 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001307 Overridden.append(overridden_methods_begin(CXXMethod),
1308 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001309 return;
1310 }
1311
1312 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1313 if (!Method)
1314 return;
1315
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001316 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1317 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001318 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001319}
1320
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001321void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1322 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1323 assert(!Import->isFromASTFile() && "Non-local import declaration");
1324 if (!FirstLocalImport) {
1325 FirstLocalImport = Import;
1326 LastLocalImport = Import;
1327 return;
1328 }
1329
1330 LastLocalImport->NextLocalImport = Import;
1331 LastLocalImport = Import;
1332}
1333
Chris Lattner53cfe802007-07-18 17:52:12 +00001334//===----------------------------------------------------------------------===//
1335// Type Sizing and Analysis
1336//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001337
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001338/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1339/// scalar floating point type.
1340const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001341 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001342 assert(BT && "Not a floating point type!");
1343 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001344 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001345 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001346 case BuiltinType::Float: return Target->getFloatFormat();
1347 case BuiltinType::Double: return Target->getDoubleFormat();
1348 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001349 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001350 }
1351}
1352
Rafael Espindola71eccb32013-08-08 19:53:46 +00001353CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001354 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001355
John McCall94268702010-10-08 18:24:19 +00001356 bool UseAlignAttrOnly = false;
1357 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1358 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001359
John McCall94268702010-10-08 18:24:19 +00001360 // __attribute__((aligned)) can increase or decrease alignment
1361 // *except* on a struct or struct member, where it only increases
1362 // alignment unless 'packed' is also specified.
1363 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001364 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001365 // ignore that possibility; Sema should diagnose it.
1366 if (isa<FieldDecl>(D)) {
1367 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1368 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1369 } else {
1370 UseAlignAttrOnly = true;
1371 }
1372 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001373 else if (isa<FieldDecl>(D))
1374 UseAlignAttrOnly =
1375 D->hasAttr<PackedAttr>() ||
1376 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001377
John McCall4e819612011-01-20 07:57:12 +00001378 // If we're using the align attribute only, just ignore everything
1379 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001380 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001381 // do nothing
1382
John McCall94268702010-10-08 18:24:19 +00001383 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001384 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001385 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001386 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001387 T = RT->getPointeeType();
1388 else
1389 T = getPointerType(RT->getPointeeType());
1390 }
Richard Smithf6d70302014-06-10 23:34:28 +00001391 QualType BaseT = getBaseElementType(T);
1392 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001393 // Adjust alignments of declarations with array type by the
1394 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001395 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001396 unsigned MinWidth = Target->getLargeArrayMinWidth();
1397 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001398 if (isa<VariableArrayType>(arrayType))
1399 Align = std::max(Align, Target->getLargeArrayAlign());
1400 else if (isa<ConstantArrayType>(arrayType) &&
1401 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1402 Align = std::max(Align, Target->getLargeArrayAlign());
1403 }
John McCall33ddac02011-01-19 10:06:00 +00001404 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001405 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001406 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001407 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001408 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1409 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001410 }
John McCall4e819612011-01-20 07:57:12 +00001411
1412 // Fields can be subject to extra alignment constraints, like if
1413 // the field is packed, the struct is packed, or the struct has a
1414 // a max-field-alignment constraint (#pragma pack). So calculate
1415 // the actual alignment of the field within the struct, and then
1416 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001417 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1418 const RecordDecl *Parent = Field->getParent();
1419 // We can only produce a sensible answer if the record is valid.
1420 if (!Parent->isInvalidDecl()) {
1421 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001422
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001423 // Start with the record's overall alignment.
1424 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001425
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001426 // Use the GCD of that and the offset within the record.
1427 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1428 if (Offset > 0) {
1429 // Alignment is always a power of 2, so the GCD will be a power of 2,
1430 // which means we get to do this crazy thing instead of Euclid's.
1431 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1432 if (LowBitOfOffset < FieldAlign)
1433 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1434 }
1435
1436 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001437 }
Charles Davis3fc51072010-02-23 04:52:00 +00001438 }
Chris Lattner68061312009-01-24 21:53:27 +00001439 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001440
Ken Dyckcc56c542011-01-15 18:38:59 +00001441 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001442}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001443
John McCallf1249922012-08-21 04:10:00 +00001444// getTypeInfoDataSizeInChars - Return the size of a type, in
1445// chars. If the type is a record, its data size is returned. This is
1446// the size of the memcpy that's performed when assigning this type
1447// using a trivial copy/move assignment operator.
1448std::pair<CharUnits, CharUnits>
1449ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1450 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1451
1452 // In C++, objects can sometimes be allocated into the tail padding
1453 // of a base-class subobject. We decide whether that's possible
1454 // during class layout, so here we can just trust the layout results.
1455 if (getLangOpts().CPlusPlus) {
1456 if (const RecordType *RT = T->getAs<RecordType>()) {
1457 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1458 sizeAndAlign.first = layout.getDataSize();
1459 }
1460 }
1461
1462 return sizeAndAlign;
1463}
1464
Richard Trieu04d2d942013-05-14 21:59:17 +00001465/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1466/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1467std::pair<CharUnits, CharUnits>
1468static getConstantArrayInfoInChars(const ASTContext &Context,
1469 const ConstantArrayType *CAT) {
1470 std::pair<CharUnits, CharUnits> EltInfo =
1471 Context.getTypeInfoInChars(CAT->getElementType());
1472 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001473 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1474 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001475 "Overflow in array type char size evaluation");
1476 uint64_t Width = EltInfo.first.getQuantity() * Size;
1477 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001478 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1479 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001480 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001481 return std::make_pair(CharUnits::fromQuantity(Width),
1482 CharUnits::fromQuantity(Align));
1483}
1484
John McCall87fe5d52010-05-20 01:18:31 +00001485std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001486ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001487 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1488 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001489 TypeInfo Info = getTypeInfo(T);
1490 return std::make_pair(toCharUnitsFromBits(Info.Width),
1491 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001492}
1493
1494std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001495ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001496 return getTypeInfoInChars(T.getTypePtr());
1497}
1498
David Majnemer34b57492014-07-30 01:30:47 +00001499bool ASTContext::isAlignmentRequired(const Type *T) const {
1500 return getTypeInfo(T).AlignIsRequired;
1501}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001502
David Majnemer34b57492014-07-30 01:30:47 +00001503bool ASTContext::isAlignmentRequired(QualType T) const {
1504 return isAlignmentRequired(T.getTypePtr());
1505}
1506
1507TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001508 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1509 if (I != MemoizedTypeInfo.end())
1510 return I->second;
1511
1512 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1513 TypeInfo TI = getTypeInfoImpl(T);
1514 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001515 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001516}
1517
1518/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1519/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001520///
1521/// FIXME: Pointers into different addr spaces could have different sizes and
1522/// alignment requirements: getPointerInfo should take an AddrSpace, this
1523/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001524TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1525 uint64_t Width = 0;
1526 unsigned Align = 8;
1527 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001528 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001529#define TYPE(Class, Base)
1530#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001531#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001532#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001533#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1534 case Type::Class: \
1535 assert(!T->isDependentType() && "should not see dependent types here"); \
1536 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001537#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001538 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001539
Chris Lattner355332d2007-07-13 22:27:08 +00001540 case Type::FunctionNoProto:
1541 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001542 // GCC extension: alignof(function) = 32 bits
1543 Width = 0;
1544 Align = 32;
1545 break;
1546
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001547 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001548 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001549 Width = 0;
1550 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1551 break;
1552
Steve Naroff5c131802007-08-30 01:06:46 +00001553 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001554 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001555
David Majnemer34b57492014-07-30 01:30:47 +00001556 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001557 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001558 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001559 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001560 Width = EltInfo.Width * Size;
1561 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001562 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1563 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001564 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001565 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001566 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001567 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001568 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001569 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001570 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1571 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001572 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001573 // If the alignment is not a power of 2, round up to the next power of 2.
1574 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001575 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001576 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001577 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001578 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001579 // Adjust the alignment based on the target max.
1580 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1581 if (TargetVectorAlign && TargetVectorAlign < Align)
1582 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001583 break;
1584 }
Chris Lattner647fb222007-07-18 18:26:58 +00001585
Chris Lattner7570e9c2008-03-08 08:52:55 +00001586 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001587 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001588 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001589 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001590 // GCC extension: alignof(void) = 8 bits.
1591 Width = 0;
1592 Align = 8;
1593 break;
1594
Chris Lattner6a4f7452007-12-19 19:23:28 +00001595 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001596 Width = Target->getBoolWidth();
1597 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001598 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001599 case BuiltinType::Char_S:
1600 case BuiltinType::Char_U:
1601 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001602 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001603 Width = Target->getCharWidth();
1604 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001605 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001606 case BuiltinType::WChar_S:
1607 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001608 Width = Target->getWCharWidth();
1609 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001610 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001611 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001612 Width = Target->getChar16Width();
1613 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001614 break;
1615 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001616 Width = Target->getChar32Width();
1617 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001618 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001619 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001620 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001621 Width = Target->getShortWidth();
1622 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001623 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001624 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001625 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001626 Width = Target->getIntWidth();
1627 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001628 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001629 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001630 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001631 Width = Target->getLongWidth();
1632 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001633 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001634 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001635 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001636 Width = Target->getLongLongWidth();
1637 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001638 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001639 case BuiltinType::Int128:
1640 case BuiltinType::UInt128:
1641 Width = 128;
1642 Align = 128; // int128_t is 128-bit aligned on all targets.
1643 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001644 case BuiltinType::Half:
1645 Width = Target->getHalfWidth();
1646 Align = Target->getHalfAlign();
1647 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001648 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001649 Width = Target->getFloatWidth();
1650 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001651 break;
1652 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001653 Width = Target->getDoubleWidth();
1654 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001655 break;
1656 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001657 Width = Target->getLongDoubleWidth();
1658 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001659 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001660 case BuiltinType::Float128:
1661 Width = Target->getFloat128Width();
1662 Align = Target->getFloat128Align();
1663 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:
Alexey Bader954ba212016-04-08 13:40:33 +00001684#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1685 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00001686#include "clang/Basic/OpenCLImageTypes.def"
Alexey Bader954ba212016-04-08 13:40:33 +00001687
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001688 // Currently these types are pointers to opaque types.
1689 Width = Target->getPointerWidth(0);
1690 Align = Target->getPointerAlign(0);
1691 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001692 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001693 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001694 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001695 Width = Target->getPointerWidth(0);
1696 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001697 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001698 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001699 unsigned AS = getTargetAddressSpace(
1700 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001701 Width = Target->getPointerWidth(AS);
1702 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001703 break;
1704 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001705 case Type::LValueReference:
1706 case Type::RValueReference: {
1707 // alignof and sizeof should never enter this code path here, so we go
1708 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001709 unsigned AS = getTargetAddressSpace(
1710 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001711 Width = Target->getPointerWidth(AS);
1712 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001713 break;
1714 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001715 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001716 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001717 Width = Target->getPointerWidth(AS);
1718 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001719 break;
1720 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001721 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001722 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001723 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001724 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001725 }
Chris Lattner647fb222007-07-18 18:26:58 +00001726 case Type::Complex: {
1727 // Complex types have the same alignment as their elements, but twice the
1728 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001729 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1730 Width = EltInfo.Width * 2;
1731 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001732 break;
1733 }
John McCall8b07ec22010-05-15 11:32:37 +00001734 case Type::ObjCObject:
1735 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001736 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001737 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001738 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001739 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001740 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001741 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001742 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001743 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001744 break;
1745 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001746 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001747 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001748 const TagType *TT = cast<TagType>(T);
1749
1750 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001751 Width = 8;
1752 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001753 break;
1754 }
Mike Stump11289f42009-09-09 15:08:12 +00001755
David Majnemer475b25e2015-01-21 10:54:38 +00001756 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1757 const EnumDecl *ED = ET->getDecl();
1758 TypeInfo Info =
1759 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1760 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1761 Info.Align = AttrAlign;
1762 Info.AlignIsRequired = true;
1763 }
1764 return Info;
1765 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001766
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001767 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001768 const RecordDecl *RD = RT->getDecl();
1769 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001770 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001771 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001772 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001773 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001774 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001775
Chris Lattner63d2b362009-10-22 05:17:15 +00001776 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001777 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1778 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001779
Richard Smith30482bc2011-02-20 03:19:35 +00001780 case Type::Auto: {
1781 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001782 assert(!A->getDeducedType().isNull() &&
1783 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001784 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001785 }
1786
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001787 case Type::Paren:
1788 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1789
Douglas Gregoref462e62009-04-30 17:32:17 +00001790 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001791 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001792 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001793 // If the typedef has an aligned attribute on it, it overrides any computed
1794 // alignment we have. This violates the GCC documentation (which says that
1795 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001796 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001797 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001798 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001799 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001800 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001801 AlignIsRequired = Info.AlignIsRequired;
1802 }
David Majnemer34b57492014-07-30 01:30:47 +00001803 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001804 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001805 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001806
Abramo Bagnara6150c882010-05-11 21:36:43 +00001807 case Type::Elaborated:
1808 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001809
John McCall81904512011-01-06 01:58:22 +00001810 case Type::Attributed:
1811 return getTypeInfo(
1812 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1813
Eli Friedman0dfb8892011-10-06 23:00:33 +00001814 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001815 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001816 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1817 Width = Info.Width;
1818 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001819
1820 // If the size of the type doesn't exceed the platform's max
1821 // atomic promotion width, make the size and alignment more
1822 // favorable to atomic operations:
1823 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1824 // Round the size up to a power of 2.
1825 if (!llvm::isPowerOf2_64(Width))
1826 Width = llvm::NextPowerOf2(Width);
1827
1828 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001829 Align = static_cast<unsigned>(Width);
1830 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001831 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001832 break;
1833
1834 case Type::Pipe: {
1835 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1836 Width = Info.Width;
1837 Align = Info.Align;
1838 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001839
Douglas Gregoref462e62009-04-30 17:32:17 +00001840 }
Mike Stump11289f42009-09-09 15:08:12 +00001841
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001842 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001843 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001844}
1845
Alexey Bataev00396512015-07-02 03:40:19 +00001846unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1847 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1848 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1849 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1850 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1851 getTargetInfo().getABI() == "elfv1-qpx" &&
1852 T->isSpecificBuiltinType(BuiltinType::Double))
1853 SimdAlign = 256;
1854 return SimdAlign;
1855}
1856
Ken Dyckcc56c542011-01-15 18:38:59 +00001857/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1858CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1859 return CharUnits::fromQuantity(BitSize / getCharWidth());
1860}
1861
Ken Dyckb0fcc592011-02-11 01:54:29 +00001862/// toBits - Convert a size in characters to a size in characters.
1863int64_t ASTContext::toBits(CharUnits CharSize) const {
1864 return CharSize.getQuantity() * getCharWidth();
1865}
1866
Ken Dyck8c89d592009-12-22 14:23:30 +00001867/// getTypeSizeInChars - Return the size of the specified type, in characters.
1868/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001869CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001870 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001871}
Jay Foad39c79802011-01-12 09:06:06 +00001872CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001873 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001874}
1875
Ken Dycka6046ab2010-01-26 17:25:18 +00001876/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001877/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001878CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001879 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001880}
Jay Foad39c79802011-01-12 09:06:06 +00001881CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001882 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001883}
1884
Chris Lattnera3402cd2009-01-27 18:08:34 +00001885/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1886/// type for the current target in bits. This can be different than the ABI
1887/// alignment in cases where it is beneficial for performance to overalign
1888/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001889unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001890 TypeInfo TI = getTypeInfo(T);
1891 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001892
David Majnemere1544562015-04-24 01:25:05 +00001893 T = T->getBaseElementTypeUnsafe();
1894
1895 // The preferred alignment of member pointers is that of a pointer.
1896 if (T->isMemberPointerType())
1897 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1898
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00001899 if (!Target->allowsLargerPreferedTypeAlignment())
1900 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001901
Eli Friedman7ab09572009-05-25 21:27:19 +00001902 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001903 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001904 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00001905 if (const EnumType *ET = T->getAs<EnumType>())
1906 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00001907 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001908 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1909 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001910 // Don't increase the alignment if an alignment attribute was specified on a
1911 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00001912 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00001913 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001914
Chris Lattnera3402cd2009-01-27 18:08:34 +00001915 return ABIAlign;
1916}
1917
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001918/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1919/// for __attribute__((aligned)) on this target, to be used if no alignment
1920/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00001921unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00001922 return getTargetInfo().getDefaultAlignForAttributeAligned();
1923}
1924
Ulrich Weigandfa806422013-05-06 16:23:57 +00001925/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1926/// to a global variable of the specified type.
1927unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1928 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1929}
1930
1931/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1932/// should be given to a global variable of the specified type.
1933CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1934 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1935}
1936
David Majnemer08ef2ba2015-06-23 20:34:18 +00001937CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1938 CharUnits Offset = CharUnits::Zero();
1939 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1940 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1941 Offset += Layout->getBaseClassOffset(Base);
1942 Layout = &getASTRecordLayout(Base);
1943 }
1944 return Offset;
1945}
1946
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001947/// DeepCollectObjCIvars -
1948/// This routine first collects all declared, but not synthesized, ivars in
1949/// super class and then collects all ivars, including those synthesized for
1950/// current class. This routine is used for implementation of current class
1951/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001952///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001953void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1954 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001955 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001956 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1957 DeepCollectObjCIvars(SuperClass, false, Ivars);
1958 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00001959 for (const auto *I : OI->ivars())
1960 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001961 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001962 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001963 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001964 Iv= Iv->getNextIvar())
1965 Ivars.push_back(Iv);
1966 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001967}
1968
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001969/// CollectInheritedProtocols - Collect all protocols in current class and
1970/// those inherited by it.
1971void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001972 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001973 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001974 // We can use protocol_iterator here instead of
1975 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001976 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001977 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001978 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001979
1980 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001981 for (const auto *Cat : OI->visible_categories())
1982 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001983
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001984 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1985 while (SD) {
1986 CollectInheritedProtocols(SD, Protocols);
1987 SD = SD->getSuperClass();
1988 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001989 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00001990 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001991 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001992 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001993 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00001994 // Insert the protocol.
1995 if (!Protocols.insert(
1996 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1997 return;
1998
1999 for (auto *Proto : OP->protocols())
2000 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002001 }
2002}
2003
Jay Foad39c79802011-01-12 09:06:06 +00002004unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002005 unsigned count = 0;
2006 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002007 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002008 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002009
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002010 // Count ivar defined in this class's implementation. This
2011 // includes synthesized ivars.
2012 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002013 count += ImplDecl->ivar_size();
2014
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002015 return count;
2016}
2017
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002018bool ASTContext::isSentinelNullExpr(const Expr *E) {
2019 if (!E)
2020 return false;
2021
2022 // nullptr_t is always treated as null.
2023 if (E->getType()->isNullPtrType()) return true;
2024
2025 if (E->getType()->isAnyPointerType() &&
2026 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2027 Expr::NPC_ValueDependentIsNull))
2028 return true;
2029
2030 // Unfortunately, __null has type 'int'.
2031 if (isa<GNUNullExpr>(E)) return true;
2032
2033 return false;
2034}
2035
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002036/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2037ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2038 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2039 I = ObjCImpls.find(D);
2040 if (I != ObjCImpls.end())
2041 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002042 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002043}
2044/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2045ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2046 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2047 I = ObjCImpls.find(D);
2048 if (I != ObjCImpls.end())
2049 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002050 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002051}
2052
2053/// \brief Set the implementation of ObjCInterfaceDecl.
2054void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2055 ObjCImplementationDecl *ImplD) {
2056 assert(IFaceD && ImplD && "Passed null params");
2057 ObjCImpls[IFaceD] = ImplD;
2058}
2059/// \brief Set the implementation of ObjCCategoryDecl.
2060void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2061 ObjCCategoryImplDecl *ImplD) {
2062 assert(CatD && ImplD && "Passed null params");
2063 ObjCImpls[CatD] = ImplD;
2064}
2065
Chandler Carruth21c90602015-12-30 03:24:14 +00002066const ObjCMethodDecl *
2067ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2068 return ObjCMethodRedecls.lookup(MD);
2069}
2070
2071void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2072 const ObjCMethodDecl *Redecl) {
2073 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2074 ObjCMethodRedecls[MD] = Redecl;
2075}
2076
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002077const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2078 const NamedDecl *ND) const {
2079 if (const ObjCInterfaceDecl *ID =
2080 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002081 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002082 if (const ObjCCategoryDecl *CD =
2083 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002084 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002085 if (const ObjCImplDecl *IMD =
2086 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002087 return IMD->getClassInterface();
2088
Craig Topper36250ad2014-05-12 05:36:57 +00002089 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002090}
2091
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002092/// \brief Get the copy initialization expression of VarDecl,or NULL if
2093/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002094Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002095 assert(VD && "Passed null params");
2096 assert(VD->hasAttr<BlocksAttr>() &&
2097 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002098 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002099 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002100 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002101}
2102
2103/// \brief Set the copy inialization expression of a block var decl.
2104void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2105 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002106 assert(VD->hasAttr<BlocksAttr>() &&
2107 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002108 BlockVarCopyInits[VD] = Init;
2109}
2110
John McCallbcd03502009-12-07 02:54:59 +00002111TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002112 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002113 if (!DataSize)
2114 DataSize = TypeLoc::getFullDataSizeForType(T);
2115 else
2116 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002117 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002118
John McCallbcd03502009-12-07 02:54:59 +00002119 TypeSourceInfo *TInfo =
2120 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2121 new (TInfo) TypeSourceInfo(T);
2122 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002123}
2124
John McCallbcd03502009-12-07 02:54:59 +00002125TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002126 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002127 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002128 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002129 return DI;
2130}
2131
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002132const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002133ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002134 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002135}
2136
2137const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002138ASTContext::getASTObjCImplementationLayout(
2139 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002140 return getObjCLayout(D->getClassInterface(), D);
2141}
2142
Chris Lattner983a8bb2007-07-13 22:13:22 +00002143//===----------------------------------------------------------------------===//
2144// Type creation/memoization methods
2145//===----------------------------------------------------------------------===//
2146
Jay Foad39c79802011-01-12 09:06:06 +00002147QualType
John McCall33ddac02011-01-19 10:06:00 +00002148ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2149 unsigned fastQuals = quals.getFastQualifiers();
2150 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002151
2152 // Check if we've already instantiated this type.
2153 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002154 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002155 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002156 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2157 assert(eq->getQualifiers() == quals);
2158 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002159 }
2160
John McCall33ddac02011-01-19 10:06:00 +00002161 // If the base type is not canonical, make the appropriate canonical type.
2162 QualType canon;
2163 if (!baseType->isCanonicalUnqualified()) {
2164 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002165 canonSplit.Quals.addConsistentQualifiers(quals);
2166 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002167
2168 // Re-find the insert position.
2169 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2170 }
2171
2172 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2173 ExtQualNodes.InsertNode(eq, insertPos);
2174 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002175}
2176
Jay Foad39c79802011-01-12 09:06:06 +00002177QualType
2178ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002179 QualType CanT = getCanonicalType(T);
2180 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002181 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002182
John McCall8ccfcb52009-09-24 19:53:00 +00002183 // If we are composing extended qualifiers together, merge together
2184 // into one ExtQuals node.
2185 QualifierCollector Quals;
2186 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002187
John McCall8ccfcb52009-09-24 19:53:00 +00002188 // If this type already has an address space specified, it cannot get
2189 // another one.
2190 assert(!Quals.hasAddressSpace() &&
2191 "Type cannot be in multiple addr spaces!");
2192 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002193
John McCall8ccfcb52009-09-24 19:53:00 +00002194 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002195}
2196
Chris Lattnerd60183d2009-02-18 22:53:11 +00002197QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002198 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002199 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002200 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002201 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002202
John McCall53fa7142010-12-24 02:08:15 +00002203 if (const PointerType *ptr = T->getAs<PointerType>()) {
2204 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002205 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002206 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2207 return getPointerType(ResultType);
2208 }
2209 }
Mike Stump11289f42009-09-09 15:08:12 +00002210
John McCall8ccfcb52009-09-24 19:53:00 +00002211 // If we are composing extended qualifiers together, merge together
2212 // into one ExtQuals node.
2213 QualifierCollector Quals;
2214 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002215
John McCall8ccfcb52009-09-24 19:53:00 +00002216 // If this type already has an ObjCGC specified, it cannot get
2217 // another one.
2218 assert(!Quals.hasObjCGCAttr() &&
2219 "Type cannot have multiple ObjCGCs!");
2220 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002221
John McCall8ccfcb52009-09-24 19:53:00 +00002222 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002223}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002224
John McCall4f5019e2010-12-19 02:44:49 +00002225const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2226 FunctionType::ExtInfo Info) {
2227 if (T->getExtInfo() == Info)
2228 return T;
2229
2230 QualType Result;
2231 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002232 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002233 } else {
2234 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2235 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2236 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002237 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002238 }
2239
2240 return cast<FunctionType>(Result.getTypePtr());
2241}
2242
Richard Smith2a7d4812013-05-04 07:00:32 +00002243void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2244 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002245 FD = FD->getMostRecentDecl();
2246 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002247 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2248 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002249 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002250 if (FunctionDecl *Next = FD->getPreviousDecl())
2251 FD = Next;
2252 else
2253 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002254 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002255 if (ASTMutationListener *L = getASTMutationListener())
2256 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002257}
2258
Richard Smith0b3a4622014-11-13 20:01:57 +00002259/// Get a function type and produce the equivalent function type with the
2260/// specified exception specification. Type sugar that can be present on a
2261/// declaration of a function with an exception specification is permitted
2262/// and preserved. Other type sugar (for instance, typedefs) is not.
2263static QualType getFunctionTypeWithExceptionSpec(
2264 ASTContext &Context, QualType Orig,
2265 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2266 // Might have some parens.
2267 if (auto *PT = dyn_cast<ParenType>(Orig))
2268 return Context.getParenType(
2269 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2270
2271 // Might have a calling-convention attribute.
2272 if (auto *AT = dyn_cast<AttributedType>(Orig))
2273 return Context.getAttributedType(
2274 AT->getAttrKind(),
2275 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2276 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2277 ESI));
2278
2279 // Anything else must be a function type. Rebuild it with the new exception
2280 // specification.
2281 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2282 return Context.getFunctionType(
2283 Proto->getReturnType(), Proto->getParamTypes(),
2284 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2285}
2286
2287void ASTContext::adjustExceptionSpec(
2288 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2289 bool AsWritten) {
2290 // Update the type.
2291 QualType Updated =
2292 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2293 FD->setType(Updated);
2294
2295 if (!AsWritten)
2296 return;
2297
2298 // Update the type in the type source information too.
2299 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2300 // If the type and the type-as-written differ, we may need to update
2301 // the type-as-written too.
2302 if (TSInfo->getType() != FD->getType())
2303 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2304
2305 // FIXME: When we get proper type location information for exceptions,
2306 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2307 // up the TypeSourceInfo;
2308 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2309 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2310 "TypeLoc size mismatch from updating exception specification");
2311 TSInfo->overrideType(Updated);
2312 }
2313}
2314
Chris Lattnerc6395932007-06-22 20:56:16 +00002315/// getComplexType - Return the uniqued reference to the type for a complex
2316/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002317QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002318 // Unique pointers, to guarantee there is only one pointer of a particular
2319 // structure.
2320 llvm::FoldingSetNodeID ID;
2321 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002322
Craig Topper36250ad2014-05-12 05:36:57 +00002323 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002324 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2325 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002326
Chris Lattnerc6395932007-06-22 20:56:16 +00002327 // If the pointee type isn't canonical, this won't be a canonical type either,
2328 // so fill in the canonical type field.
2329 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002330 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002331 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002332
Chris Lattnerc6395932007-06-22 20:56:16 +00002333 // Get the new insert position for the node we care about.
2334 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002335 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002336 }
John McCall90d1c2d2009-09-24 23:30:46 +00002337 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002338 Types.push_back(New);
2339 ComplexTypes.InsertNode(New, InsertPos);
2340 return QualType(New, 0);
2341}
2342
Chris Lattner970e54e2006-11-12 00:37:36 +00002343/// getPointerType - Return the uniqued reference to the type for a pointer to
2344/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002345QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002346 // Unique pointers, to guarantee there is only one pointer of a particular
2347 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002348 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002349 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002350
Craig Topper36250ad2014-05-12 05:36:57 +00002351 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002352 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002353 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002354
Chris Lattner7ccecb92006-11-12 08:50:50 +00002355 // If the pointee type isn't canonical, this won't be a canonical type either,
2356 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002357 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002358 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002359 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002360
Bob Wilsonc8541f22013-03-15 17:12:43 +00002361 // Get the new insert position for the node we care about.
2362 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002363 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002364 }
John McCall90d1c2d2009-09-24 23:30:46 +00002365 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002366 Types.push_back(New);
2367 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002368 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002369}
2370
Reid Kleckner0503a872013-12-05 01:23:43 +00002371QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2372 llvm::FoldingSetNodeID ID;
2373 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002374 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002375 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2376 if (AT)
2377 return QualType(AT, 0);
2378
2379 QualType Canonical = getCanonicalType(New);
2380
2381 // Get the new insert position for the node we care about.
2382 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002383 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002384
2385 AT = new (*this, TypeAlignment)
2386 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2387 Types.push_back(AT);
2388 AdjustedTypes.InsertNode(AT, InsertPos);
2389 return QualType(AT, 0);
2390}
2391
Reid Kleckner8a365022013-06-24 17:51:48 +00002392QualType ASTContext::getDecayedType(QualType T) const {
2393 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2394
Reid Kleckner8a365022013-06-24 17:51:48 +00002395 QualType Decayed;
2396
2397 // C99 6.7.5.3p7:
2398 // A declaration of a parameter as "array of type" shall be
2399 // adjusted to "qualified pointer to type", where the type
2400 // qualifiers (if any) are those specified within the [ and ] of
2401 // the array type derivation.
2402 if (T->isArrayType())
2403 Decayed = getArrayDecayedType(T);
2404
2405 // C99 6.7.5.3p8:
2406 // A declaration of a parameter as "function returning type"
2407 // shall be adjusted to "pointer to function returning type", as
2408 // in 6.3.2.1.
2409 if (T->isFunctionType())
2410 Decayed = getPointerType(T);
2411
Reid Kleckner0503a872013-12-05 01:23:43 +00002412 llvm::FoldingSetNodeID ID;
2413 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002414 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002415 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2416 if (AT)
2417 return QualType(AT, 0);
2418
Reid Kleckner8a365022013-06-24 17:51:48 +00002419 QualType Canonical = getCanonicalType(Decayed);
2420
2421 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002422 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002423 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002424
Reid Kleckner0503a872013-12-05 01:23:43 +00002425 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2426 Types.push_back(AT);
2427 AdjustedTypes.InsertNode(AT, InsertPos);
2428 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002429}
2430
Mike Stump11289f42009-09-09 15:08:12 +00002431/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002432/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002433QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002434 assert(T->isFunctionType() && "block of function types only");
2435 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002436 // structure.
2437 llvm::FoldingSetNodeID ID;
2438 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002439
Craig Topper36250ad2014-05-12 05:36:57 +00002440 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002441 if (BlockPointerType *PT =
2442 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2443 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002444
2445 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002446 // type either so fill in the canonical type field.
2447 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002448 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002449 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002450
Steve Naroffec33ed92008-08-27 16:04:49 +00002451 // Get the new insert position for the node we care about.
2452 BlockPointerType *NewIP =
2453 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002454 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002455 }
John McCall90d1c2d2009-09-24 23:30:46 +00002456 BlockPointerType *New
2457 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002458 Types.push_back(New);
2459 BlockPointerTypes.InsertNode(New, InsertPos);
2460 return QualType(New, 0);
2461}
2462
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002463/// getLValueReferenceType - Return the uniqued reference to the type for an
2464/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002465QualType
2466ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002467 assert(getCanonicalType(T) != OverloadTy &&
2468 "Unresolved overloaded function type");
2469
Bill Wendling3708c182007-05-27 10:15:43 +00002470 // Unique pointers, to guarantee there is only one pointer of a particular
2471 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002472 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002473 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002474
Craig Topper36250ad2014-05-12 05:36:57 +00002475 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002476 if (LValueReferenceType *RT =
2477 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002478 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002479
John McCallfc93cf92009-10-22 22:37:11 +00002480 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2481
Bill Wendling3708c182007-05-27 10:15:43 +00002482 // If the referencee type isn't canonical, this won't be a canonical type
2483 // either, so fill in the canonical type field.
2484 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002485 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2486 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2487 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002488
Bill Wendling3708c182007-05-27 10:15:43 +00002489 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002490 LValueReferenceType *NewIP =
2491 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002492 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002493 }
2494
John McCall90d1c2d2009-09-24 23:30:46 +00002495 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002496 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2497 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002498 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002499 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002500
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002501 return QualType(New, 0);
2502}
2503
2504/// getRValueReferenceType - Return the uniqued reference to the type for an
2505/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002506QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002507 // Unique pointers, to guarantee there is only one pointer of a particular
2508 // structure.
2509 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002510 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002511
Craig Topper36250ad2014-05-12 05:36:57 +00002512 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002513 if (RValueReferenceType *RT =
2514 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2515 return QualType(RT, 0);
2516
John McCallfc93cf92009-10-22 22:37:11 +00002517 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2518
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002519 // If the referencee type isn't canonical, this won't be a canonical type
2520 // either, so fill in the canonical type field.
2521 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002522 if (InnerRef || !T.isCanonical()) {
2523 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2524 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002525
2526 // Get the new insert position for the node we care about.
2527 RValueReferenceType *NewIP =
2528 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002529 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002530 }
2531
John McCall90d1c2d2009-09-24 23:30:46 +00002532 RValueReferenceType *New
2533 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002534 Types.push_back(New);
2535 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002536 return QualType(New, 0);
2537}
2538
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002539/// getMemberPointerType - Return the uniqued reference to the type for a
2540/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002541QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002542 // Unique pointers, to guarantee there is only one pointer of a particular
2543 // structure.
2544 llvm::FoldingSetNodeID ID;
2545 MemberPointerType::Profile(ID, T, Cls);
2546
Craig Topper36250ad2014-05-12 05:36:57 +00002547 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002548 if (MemberPointerType *PT =
2549 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2550 return QualType(PT, 0);
2551
2552 // If the pointee or class type isn't canonical, this won't be a canonical
2553 // type either, so fill in the canonical type field.
2554 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002555 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002556 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2557
2558 // Get the new insert position for the node we care about.
2559 MemberPointerType *NewIP =
2560 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002561 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002562 }
John McCall90d1c2d2009-09-24 23:30:46 +00002563 MemberPointerType *New
2564 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002565 Types.push_back(New);
2566 MemberPointerTypes.InsertNode(New, InsertPos);
2567 return QualType(New, 0);
2568}
2569
Mike Stump11289f42009-09-09 15:08:12 +00002570/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002571/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002572QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002573 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002574 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002575 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002576 assert((EltTy->isDependentType() ||
2577 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002578 "Constant array of VLAs is illegal!");
2579
Chris Lattnere2df3f92009-05-13 04:12:56 +00002580 // Convert the array size into a canonical width matching the pointer size for
2581 // the target.
2582 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002583 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002584 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002585
Chris Lattner23b7eb62007-06-15 23:05:46 +00002586 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002587 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002588
Craig Topper36250ad2014-05-12 05:36:57 +00002589 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002590 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002591 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002592 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002593
John McCall33ddac02011-01-19 10:06:00 +00002594 // If the element type isn't canonical or has qualifiers, this won't
2595 // be a canonical type either, so fill in the canonical type field.
2596 QualType Canon;
2597 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2598 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002599 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002600 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002601 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002602
Chris Lattner36f8e652007-01-27 08:31:04 +00002603 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002604 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002605 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002606 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002607 }
Mike Stump11289f42009-09-09 15:08:12 +00002608
John McCall90d1c2d2009-09-24 23:30:46 +00002609 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002610 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002611 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002612 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002613 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002614}
2615
John McCall06549462011-01-18 08:40:38 +00002616/// getVariableArrayDecayedType - Turns the given type, which may be
2617/// variably-modified, into the corresponding type with all the known
2618/// sizes replaced with [*].
2619QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2620 // Vastly most common case.
2621 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002622
John McCall06549462011-01-18 08:40:38 +00002623 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002624
John McCall06549462011-01-18 08:40:38 +00002625 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002626 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002627 switch (ty->getTypeClass()) {
2628#define TYPE(Class, Base)
2629#define ABSTRACT_TYPE(Class, Base)
2630#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2631#include "clang/AST/TypeNodes.def"
2632 llvm_unreachable("didn't desugar past all non-canonical types?");
2633
2634 // These types should never be variably-modified.
2635 case Type::Builtin:
2636 case Type::Complex:
2637 case Type::Vector:
2638 case Type::ExtVector:
2639 case Type::DependentSizedExtVector:
2640 case Type::ObjCObject:
2641 case Type::ObjCInterface:
2642 case Type::ObjCObjectPointer:
2643 case Type::Record:
2644 case Type::Enum:
2645 case Type::UnresolvedUsing:
2646 case Type::TypeOfExpr:
2647 case Type::TypeOf:
2648 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002649 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002650 case Type::DependentName:
2651 case Type::InjectedClassName:
2652 case Type::TemplateSpecialization:
2653 case Type::DependentTemplateSpecialization:
2654 case Type::TemplateTypeParm:
2655 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002656 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002657 case Type::PackExpansion:
2658 llvm_unreachable("type should never be variably-modified");
2659
2660 // These types can be variably-modified but should never need to
2661 // further decay.
2662 case Type::FunctionNoProto:
2663 case Type::FunctionProto:
2664 case Type::BlockPointer:
2665 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002666 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002667 return type;
2668
2669 // These types can be variably-modified. All these modifications
2670 // preserve structure except as noted by comments.
2671 // TODO: if we ever care about optimizing VLAs, there are no-op
2672 // optimizations available here.
2673 case Type::Pointer:
2674 result = getPointerType(getVariableArrayDecayedType(
2675 cast<PointerType>(ty)->getPointeeType()));
2676 break;
2677
2678 case Type::LValueReference: {
2679 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2680 result = getLValueReferenceType(
2681 getVariableArrayDecayedType(lv->getPointeeType()),
2682 lv->isSpelledAsLValue());
2683 break;
2684 }
2685
2686 case Type::RValueReference: {
2687 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2688 result = getRValueReferenceType(
2689 getVariableArrayDecayedType(lv->getPointeeType()));
2690 break;
2691 }
2692
Eli Friedman0dfb8892011-10-06 23:00:33 +00002693 case Type::Atomic: {
2694 const AtomicType *at = cast<AtomicType>(ty);
2695 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2696 break;
2697 }
2698
John McCall06549462011-01-18 08:40:38 +00002699 case Type::ConstantArray: {
2700 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2701 result = getConstantArrayType(
2702 getVariableArrayDecayedType(cat->getElementType()),
2703 cat->getSize(),
2704 cat->getSizeModifier(),
2705 cat->getIndexTypeCVRQualifiers());
2706 break;
2707 }
2708
2709 case Type::DependentSizedArray: {
2710 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2711 result = getDependentSizedArrayType(
2712 getVariableArrayDecayedType(dat->getElementType()),
2713 dat->getSizeExpr(),
2714 dat->getSizeModifier(),
2715 dat->getIndexTypeCVRQualifiers(),
2716 dat->getBracketsRange());
2717 break;
2718 }
2719
2720 // Turn incomplete types into [*] types.
2721 case Type::IncompleteArray: {
2722 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2723 result = getVariableArrayType(
2724 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002725 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002726 ArrayType::Normal,
2727 iat->getIndexTypeCVRQualifiers(),
2728 SourceRange());
2729 break;
2730 }
2731
2732 // Turn VLA types into [*] types.
2733 case Type::VariableArray: {
2734 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2735 result = getVariableArrayType(
2736 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002737 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002738 ArrayType::Star,
2739 vat->getIndexTypeCVRQualifiers(),
2740 vat->getBracketsRange());
2741 break;
2742 }
2743 }
2744
2745 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002746 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002747}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002748
Steve Naroffcadebd02007-08-30 18:14:25 +00002749/// getVariableArrayType - Returns a non-unique reference to the type for a
2750/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002751QualType ASTContext::getVariableArrayType(QualType EltTy,
2752 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002753 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002754 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002755 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002756 // Since we don't unique expressions, it isn't possible to unique VLA's
2757 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002758 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002759
John McCall33ddac02011-01-19 10:06:00 +00002760 // Be sure to pull qualifiers off the element type.
2761 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2762 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002763 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002764 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002765 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002766 }
2767
John McCall90d1c2d2009-09-24 23:30:46 +00002768 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002769 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002770
2771 VariableArrayTypes.push_back(New);
2772 Types.push_back(New);
2773 return QualType(New, 0);
2774}
2775
Douglas Gregor4619e432008-12-05 23:32:09 +00002776/// getDependentSizedArrayType - Returns a non-unique reference to
2777/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002778/// type.
John McCall33ddac02011-01-19 10:06:00 +00002779QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2780 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002781 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002782 unsigned elementTypeQuals,
2783 SourceRange brackets) const {
2784 assert((!numElements || numElements->isTypeDependent() ||
2785 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002786 "Size must be type- or value-dependent!");
2787
John McCall33ddac02011-01-19 10:06:00 +00002788 // Dependently-sized array types that do not have a specified number
2789 // of elements will have their sizes deduced from a dependent
2790 // initializer. We do no canonicalization here at all, which is okay
2791 // because they can't be used in most locations.
2792 if (!numElements) {
2793 DependentSizedArrayType *newType
2794 = new (*this, TypeAlignment)
2795 DependentSizedArrayType(*this, elementType, QualType(),
2796 numElements, ASM, elementTypeQuals,
2797 brackets);
2798 Types.push_back(newType);
2799 return QualType(newType, 0);
2800 }
2801
2802 // Otherwise, we actually build a new type every time, but we
2803 // also build a canonical type.
2804
2805 SplitQualType canonElementType = getCanonicalType(elementType).split();
2806
Craig Topper36250ad2014-05-12 05:36:57 +00002807 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002808 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002809 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002810 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002811 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002812
John McCall33ddac02011-01-19 10:06:00 +00002813 // Look for an existing type with these properties.
2814 DependentSizedArrayType *canonTy =
2815 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002816
John McCall33ddac02011-01-19 10:06:00 +00002817 // If we don't have one, build one.
2818 if (!canonTy) {
2819 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002820 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002821 QualType(), numElements, ASM, elementTypeQuals,
2822 brackets);
2823 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2824 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002825 }
2826
John McCall33ddac02011-01-19 10:06:00 +00002827 // Apply qualifiers from the element type to the array.
2828 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002829 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002830
David Majnemer16a74702015-07-24 05:54:19 +00002831 // If we didn't need extra canonicalization for the element type or the size
2832 // expression, then just use that as our result.
2833 if (QualType(canonElementType.Ty, 0) == elementType &&
2834 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002835 return canon;
2836
2837 // Otherwise, we need to build a type which follows the spelling
2838 // of the element type.
2839 DependentSizedArrayType *sugaredType
2840 = new (*this, TypeAlignment)
2841 DependentSizedArrayType(*this, elementType, canon, numElements,
2842 ASM, elementTypeQuals, brackets);
2843 Types.push_back(sugaredType);
2844 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002845}
2846
John McCall33ddac02011-01-19 10:06:00 +00002847QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002848 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002849 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002850 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002851 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002852
Craig Topper36250ad2014-05-12 05:36:57 +00002853 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002854 if (IncompleteArrayType *iat =
2855 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2856 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002857
2858 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002859 // either, so fill in the canonical type field. We also have to pull
2860 // qualifiers off the element type.
2861 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002862
John McCall33ddac02011-01-19 10:06:00 +00002863 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2864 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002865 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002866 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002867 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002868
2869 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002870 IncompleteArrayType *existing =
2871 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2872 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002873 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002874
John McCall33ddac02011-01-19 10:06:00 +00002875 IncompleteArrayType *newType = new (*this, TypeAlignment)
2876 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002877
John McCall33ddac02011-01-19 10:06:00 +00002878 IncompleteArrayTypes.InsertNode(newType, insertPos);
2879 Types.push_back(newType);
2880 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002881}
2882
Steve Naroff91fcddb2007-07-18 18:00:27 +00002883/// getVectorType - Return the unique reference to a vector type of
2884/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002885QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002886 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002887 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002888
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002889 // Check if we've already instantiated a vector of this type.
2890 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002891 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002892
Craig Topper36250ad2014-05-12 05:36:57 +00002893 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002894 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2895 return QualType(VTP, 0);
2896
2897 // If the element type isn't canonical, this won't be a canonical type either,
2898 // so fill in the canonical type field.
2899 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002900 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002901 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002902
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002903 // Get the new insert position for the node we care about.
2904 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002905 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002906 }
John McCall90d1c2d2009-09-24 23:30:46 +00002907 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002908 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002909 VectorTypes.InsertNode(New, InsertPos);
2910 Types.push_back(New);
2911 return QualType(New, 0);
2912}
2913
Nate Begemance4d7fc2008-04-18 23:10:10 +00002914/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002915/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002916QualType
2917ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002918 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002919
Steve Naroff91fcddb2007-07-18 18:00:27 +00002920 // Check if we've already instantiated a vector of this type.
2921 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002922 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002923 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00002924 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002925 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2926 return QualType(VTP, 0);
2927
2928 // If the element type isn't canonical, this won't be a canonical type either,
2929 // so fill in the canonical type field.
2930 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002931 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002932 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002933
Steve Naroff91fcddb2007-07-18 18:00:27 +00002934 // Get the new insert position for the node we care about.
2935 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002936 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002937 }
John McCall90d1c2d2009-09-24 23:30:46 +00002938 ExtVectorType *New = new (*this, TypeAlignment)
2939 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002940 VectorTypes.InsertNode(New, InsertPos);
2941 Types.push_back(New);
2942 return QualType(New, 0);
2943}
2944
Jay Foad39c79802011-01-12 09:06:06 +00002945QualType
2946ASTContext::getDependentSizedExtVectorType(QualType vecType,
2947 Expr *SizeExpr,
2948 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002949 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002950 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002951 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002952
Craig Topper36250ad2014-05-12 05:36:57 +00002953 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00002954 DependentSizedExtVectorType *Canon
2955 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2956 DependentSizedExtVectorType *New;
2957 if (Canon) {
2958 // We already have a canonical version of this array type; use it as
2959 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002960 New = new (*this, TypeAlignment)
2961 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2962 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002963 } else {
2964 QualType CanonVecTy = getCanonicalType(vecType);
2965 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002966 New = new (*this, TypeAlignment)
2967 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2968 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002969
2970 DependentSizedExtVectorType *CanonCheck
2971 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2972 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2973 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002974 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2975 } else {
2976 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2977 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002978 New = new (*this, TypeAlignment)
2979 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002980 }
2981 }
Mike Stump11289f42009-09-09 15:08:12 +00002982
Douglas Gregor758a8692009-06-17 21:51:59 +00002983 Types.push_back(New);
2984 return QualType(New, 0);
2985}
2986
John McCall18afab72016-03-01 00:49:02 +00002987/// \brief Determine whether \p T is canonical as the result type of a function.
2988static bool isCanonicalResultType(QualType T) {
2989 return T.isCanonical() &&
2990 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2991 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2992}
2993
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002994/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002995///
Jay Foad39c79802011-01-12 09:06:06 +00002996QualType
2997ASTContext::getFunctionNoProtoType(QualType ResultTy,
2998 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002999 // Unique functions, to guarantee there is only one function of a particular
3000 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003001 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003002 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003003
Craig Topper36250ad2014-05-12 05:36:57 +00003004 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003005 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003006 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003007 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003008
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003009 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003010 if (!isCanonicalResultType(ResultTy)) {
3011 Canonical =
3012 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003013
Chris Lattner47955de2007-01-27 08:37:20 +00003014 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003015 FunctionNoProtoType *NewIP =
3016 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003017 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003018 }
Mike Stump11289f42009-09-09 15:08:12 +00003019
John McCall90d1c2d2009-09-24 23:30:46 +00003020 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003021 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003022 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003023 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003024 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003025}
3026
Douglas Gregora602a152015-10-01 20:20:47 +00003027CanQualType
3028ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3029 CanQualType CanResultType = getCanonicalType(ResultType);
3030
3031 // Canonical result types do not have ARC lifetime qualifiers.
3032 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3033 Qualifiers Qs = CanResultType.getQualifiers();
3034 Qs.removeObjCLifetime();
3035 return CanQualType::CreateUnsafe(
3036 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3037 }
3038
3039 return CanResultType;
3040}
3041
Jay Foad39c79802011-01-12 09:06:06 +00003042QualType
Jordan Rose5c382722013-03-08 21:51:21 +00003043ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00003044 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003045 size_t NumArgs = ArgArray.size();
3046
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003047 // Unique functions, to guarantee there is only one function of a particular
3048 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003049 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00003050 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3051 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00003052
Craig Topper36250ad2014-05-12 05:36:57 +00003053 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003054 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003055 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003056 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003057
3058 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00003059 bool isCanonical =
Richard Smith8acb4282014-07-31 21:57:55 +00003060 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00003061 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003062 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003063 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003064 isCanonical = false;
3065
3066 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003067 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003068 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00003069 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003070 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003071 CanonicalArgs.reserve(NumArgs);
3072 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003073 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003074
John McCalldb40c7f2010-12-14 08:05:40 +00003075 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003076 CanonicalEPI.HasTrailingReturn = false;
Richard Smith8acb4282014-07-31 21:57:55 +00003077 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003078
Douglas Gregora602a152015-10-01 20:20:47 +00003079 // Adjust the canonical function result type.
3080 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Jordan Rose5c382722013-03-08 21:51:21 +00003081 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003082
Chris Lattnerfd4de792007-01-27 01:15:32 +00003083 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003084 FunctionProtoType *NewIP =
3085 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003086 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003087 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003088
John McCall31168b02011-06-15 23:02:42 +00003089 // FunctionProtoType objects are allocated with extra bytes after
3090 // them for three variable size arrays at the end:
3091 // - parameter types
3092 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003093 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003094 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003095 // expression, or information used to resolve the exception
3096 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003097 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003098 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003099
Richard Smith8acb4282014-07-31 21:57:55 +00003100 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3101 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3102 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003103 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003104 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003105 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003106 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003107 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003108 }
John McCall18afab72016-03-01 00:49:02 +00003109
3110 // Put the ExtParameterInfos last. If all were equal, it would make
3111 // more sense to put these before the exception specification, because
3112 // it's much easier to skip past them compared to the elaborate switch
3113 // required to skip the exception specification. However, all is not
3114 // equal; ExtParameterInfos are used to model very uncommon features,
3115 // and it's better not to burden the more common paths.
3116 if (EPI.ExtParameterInfos) {
3117 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3118 }
John McCall31168b02011-06-15 23:02:42 +00003119
John McCalldb40c7f2010-12-14 08:05:40 +00003120 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003121 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003122 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003123 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003124 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003125 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003126}
Chris Lattneref51c202006-11-10 07:17:23 +00003127
Xiuli Pan9c14e282016-01-09 12:53:17 +00003128/// Return pipe type for the specified type.
3129QualType ASTContext::getPipeType(QualType T) const {
3130 llvm::FoldingSetNodeID ID;
3131 PipeType::Profile(ID, T);
3132
3133 void *InsertPos = 0;
3134 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3135 return QualType(PT, 0);
3136
3137 // If the pipe element type isn't canonical, this won't be a canonical type
3138 // either, so fill in the canonical type field.
3139 QualType Canonical;
3140 if (!T.isCanonical()) {
3141 Canonical = getPipeType(getCanonicalType(T));
3142
3143 // Get the new insert position for the node we care about.
3144 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3145 assert(!NewIP && "Shouldn't be in the map!");
3146 (void)NewIP;
3147 }
3148 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3149 Types.push_back(New);
3150 PipeTypes.InsertNode(New, InsertPos);
3151 return QualType(New, 0);
3152}
3153
John McCalle78aac42010-03-10 03:28:59 +00003154#ifndef NDEBUG
3155static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3156 if (!isa<CXXRecordDecl>(D)) return false;
3157 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3158 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3159 return true;
3160 if (RD->getDescribedClassTemplate() &&
3161 !isa<ClassTemplateSpecializationDecl>(RD))
3162 return true;
3163 return false;
3164}
3165#endif
3166
3167/// getInjectedClassNameType - Return the unique reference to the
3168/// injected class name type for the specified templated declaration.
3169QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003170 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003171 assert(NeedsInjectedClassNameType(Decl));
3172 if (Decl->TypeForDecl) {
3173 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003174 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003175 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3176 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3177 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3178 } else {
John McCall424cec92011-01-19 06:33:43 +00003179 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003180 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003181 Decl->TypeForDecl = newType;
3182 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003183 }
3184 return QualType(Decl->TypeForDecl, 0);
3185}
3186
Douglas Gregor83a586e2008-04-13 21:07:44 +00003187/// getTypeDeclType - Return the unique reference to the type for the
3188/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003189QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003190 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003191 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003192
Richard Smithdda56e42011-04-15 14:24:37 +00003193 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003194 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003195
John McCall96f0b5f2010-03-10 06:48:02 +00003196 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3197 "Template type parameter types are always available.");
3198
John McCall81e38502010-02-16 03:57:14 +00003199 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003200 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003201 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003202 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003203 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003204 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003205 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003206 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003207 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003208 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3209 Decl->TypeForDecl = newType;
3210 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003211 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003212 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003213
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003214 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003215}
3216
Chris Lattner32d920b2007-01-26 02:01:53 +00003217/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003218/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003219QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003220ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3221 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003222 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003223
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003224 if (Canonical.isNull())
3225 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003226 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003227 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003228 Decl->TypeForDecl = newType;
3229 Types.push_back(newType);
3230 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003231}
3232
Jay Foad39c79802011-01-12 09:06:06 +00003233QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003234 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3235
Douglas Gregorec9fd132012-01-14 16:38:05 +00003236 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003237 if (PrevDecl->TypeForDecl)
3238 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3239
John McCall424cec92011-01-19 06:33:43 +00003240 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3241 Decl->TypeForDecl = newType;
3242 Types.push_back(newType);
3243 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003244}
3245
Jay Foad39c79802011-01-12 09:06:06 +00003246QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003247 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3248
Douglas Gregorec9fd132012-01-14 16:38:05 +00003249 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003250 if (PrevDecl->TypeForDecl)
3251 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3252
John McCall424cec92011-01-19 06:33:43 +00003253 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3254 Decl->TypeForDecl = newType;
3255 Types.push_back(newType);
3256 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003257}
3258
John McCall81904512011-01-06 01:58:22 +00003259QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3260 QualType modifiedType,
3261 QualType equivalentType) {
3262 llvm::FoldingSetNodeID id;
3263 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3264
Craig Topper36250ad2014-05-12 05:36:57 +00003265 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003266 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3267 if (type) return QualType(type, 0);
3268
3269 QualType canon = getCanonicalType(equivalentType);
3270 type = new (*this, TypeAlignment)
3271 AttributedType(canon, attrKind, modifiedType, equivalentType);
3272
3273 Types.push_back(type);
3274 AttributedTypes.InsertNode(type, insertPos);
3275
3276 return QualType(type, 0);
3277}
3278
John McCallcebee162009-10-18 09:09:24 +00003279/// \brief Retrieve a substitution-result type.
3280QualType
3281ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003282 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003283 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003284 && "replacement types must always be canonical");
3285
3286 llvm::FoldingSetNodeID ID;
3287 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003288 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003289 SubstTemplateTypeParmType *SubstParm
3290 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3291
3292 if (!SubstParm) {
3293 SubstParm = new (*this, TypeAlignment)
3294 SubstTemplateTypeParmType(Parm, Replacement);
3295 Types.push_back(SubstParm);
3296 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3297 }
3298
3299 return QualType(SubstParm, 0);
3300}
3301
Douglas Gregorada4b792011-01-14 02:55:32 +00003302/// \brief Retrieve a
3303QualType ASTContext::getSubstTemplateTypeParmPackType(
3304 const TemplateTypeParmType *Parm,
3305 const TemplateArgument &ArgPack) {
3306#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003307 for (const auto &P : ArgPack.pack_elements()) {
3308 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3309 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003310 }
3311#endif
3312
3313 llvm::FoldingSetNodeID ID;
3314 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003315 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003316 if (SubstTemplateTypeParmPackType *SubstParm
3317 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3318 return QualType(SubstParm, 0);
3319
3320 QualType Canon;
3321 if (!Parm->isCanonicalUnqualified()) {
3322 Canon = getCanonicalType(QualType(Parm, 0));
3323 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3324 ArgPack);
3325 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3326 }
3327
3328 SubstTemplateTypeParmPackType *SubstParm
3329 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3330 ArgPack);
3331 Types.push_back(SubstParm);
3332 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3333 return QualType(SubstParm, 0);
3334}
3335
Douglas Gregoreff93e02009-02-05 23:33:38 +00003336/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003337/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003338/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003339QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003340 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003341 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003342 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003343 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003344 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003345 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003346 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3347
3348 if (TypeParm)
3349 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003350
Chandler Carruth08836322011-05-01 00:51:33 +00003351 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003352 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003353 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003354
3355 TemplateTypeParmType *TypeCheck
3356 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3357 assert(!TypeCheck && "Template type parameter canonical type broken");
3358 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003359 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003360 TypeParm = new (*this, TypeAlignment)
3361 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003362
3363 Types.push_back(TypeParm);
3364 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3365
3366 return QualType(TypeParm, 0);
3367}
3368
John McCalle78aac42010-03-10 03:28:59 +00003369TypeSourceInfo *
3370ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3371 SourceLocation NameLoc,
3372 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003373 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003374 assert(!Name.getAsDependentTemplateName() &&
3375 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003376 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003377
3378 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003379 TemplateSpecializationTypeLoc TL =
3380 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003381 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003382 TL.setTemplateNameLoc(NameLoc);
3383 TL.setLAngleLoc(Args.getLAngleLoc());
3384 TL.setRAngleLoc(Args.getRAngleLoc());
3385 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3386 TL.setArgLocInfo(i, Args[i].getLocInfo());
3387 return DI;
3388}
3389
Mike Stump11289f42009-09-09 15:08:12 +00003390QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003391ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003392 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003393 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003394 assert(!Template.getAsDependentTemplateName() &&
3395 "No dependent template names here!");
3396
John McCall6b51f282009-11-23 01:53:49 +00003397 unsigned NumArgs = Args.size();
3398
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003399 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003400 ArgVec.reserve(NumArgs);
3401 for (unsigned i = 0; i != NumArgs; ++i)
3402 ArgVec.push_back(Args[i].getArgument());
3403
John McCall2408e322010-04-27 00:57:59 +00003404 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003405 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003406}
3407
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003408#ifndef NDEBUG
3409static bool hasAnyPackExpansions(const TemplateArgument *Args,
3410 unsigned NumArgs) {
3411 for (unsigned I = 0; I != NumArgs; ++I)
3412 if (Args[I].isPackExpansion())
3413 return true;
3414
3415 return true;
3416}
3417#endif
3418
John McCall0ad16662009-10-29 08:12:44 +00003419QualType
3420ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003421 const TemplateArgument *Args,
3422 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003423 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003424 assert(!Template.getAsDependentTemplateName() &&
3425 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003426 // Look through qualified template names.
3427 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3428 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003429
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003430 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003431 Template.getAsTemplateDecl() &&
3432 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003433 QualType CanonType;
3434 if (!Underlying.isNull())
3435 CanonType = getCanonicalType(Underlying);
3436 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003437 // We can get here with an alias template when the specialization contains
3438 // a pack expansion that does not match up with a parameter pack.
3439 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3440 "Caller must compute aliased type");
3441 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003442 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3443 NumArgs);
3444 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003445
Douglas Gregora8e02e72009-07-28 23:00:59 +00003446 // Allocate the (non-canonical) template specialization type, but don't
3447 // try to unique it: these types typically have location information that
3448 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003449 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3450 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003451 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003452 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003453 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003454 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3455 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003456
Douglas Gregor8bf42052009-02-09 18:46:07 +00003457 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003458 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003459}
3460
Mike Stump11289f42009-09-09 15:08:12 +00003461QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003462ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3463 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003464 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003465 assert(!Template.getAsDependentTemplateName() &&
3466 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003467
Douglas Gregore29139c2011-03-03 17:04:51 +00003468 // Look through qualified template names.
3469 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3470 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003471
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003472 // Build the canonical template specialization type.
3473 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003474 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003475 CanonArgs.reserve(NumArgs);
3476 for (unsigned I = 0; I != NumArgs; ++I)
3477 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3478
3479 // Determine whether this canonical template specialization type already
3480 // exists.
3481 llvm::FoldingSetNodeID ID;
3482 TemplateSpecializationType::Profile(ID, CanonTemplate,
3483 CanonArgs.data(), NumArgs, *this);
3484
Craig Topper36250ad2014-05-12 05:36:57 +00003485 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003486 TemplateSpecializationType *Spec
3487 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3488
3489 if (!Spec) {
3490 // Allocate a new canonical template specialization type.
3491 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3492 sizeof(TemplateArgument) * NumArgs),
3493 TypeAlignment);
3494 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3495 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003496 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003497 Types.push_back(Spec);
3498 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3499 }
3500
3501 assert(Spec->isDependentType() &&
3502 "Non-dependent template-id type must have a canonical type");
3503 return QualType(Spec, 0);
3504}
3505
3506QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003507ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3508 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003509 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003510 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003511 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003512
Craig Topper36250ad2014-05-12 05:36:57 +00003513 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003514 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003515 if (T)
3516 return QualType(T, 0);
3517
Douglas Gregorc42075a2010-02-04 18:10:26 +00003518 QualType Canon = NamedType;
3519 if (!Canon.isCanonical()) {
3520 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003521 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3522 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003523 (void)CheckT;
3524 }
3525
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003526 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003527 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003528 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003529 return QualType(T, 0);
3530}
3531
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003532QualType
Jay Foad39c79802011-01-12 09:06:06 +00003533ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003534 llvm::FoldingSetNodeID ID;
3535 ParenType::Profile(ID, InnerType);
3536
Craig Topper36250ad2014-05-12 05:36:57 +00003537 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003538 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3539 if (T)
3540 return QualType(T, 0);
3541
3542 QualType Canon = InnerType;
3543 if (!Canon.isCanonical()) {
3544 Canon = getCanonicalType(InnerType);
3545 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3546 assert(!CheckT && "Paren canonical type broken");
3547 (void)CheckT;
3548 }
3549
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003550 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003551 Types.push_back(T);
3552 ParenTypes.InsertNode(T, InsertPos);
3553 return QualType(T, 0);
3554}
3555
Douglas Gregor02085352010-03-31 20:19:30 +00003556QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3557 NestedNameSpecifier *NNS,
3558 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003559 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003560 if (Canon.isNull()) {
3561 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003562 ElaboratedTypeKeyword CanonKeyword = Keyword;
3563 if (Keyword == ETK_None)
3564 CanonKeyword = ETK_Typename;
3565
3566 if (CanonNNS != NNS || CanonKeyword != Keyword)
3567 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003568 }
3569
3570 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003571 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003572
Craig Topper36250ad2014-05-12 05:36:57 +00003573 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003574 DependentNameType *T
3575 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003576 if (T)
3577 return QualType(T, 0);
3578
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003579 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003580 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003581 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003582 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003583}
3584
Mike Stump11289f42009-09-09 15:08:12 +00003585QualType
John McCallc392f372010-06-11 00:33:02 +00003586ASTContext::getDependentTemplateSpecializationType(
3587 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003588 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003589 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003590 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003591 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003592 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003593 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3594 ArgCopy.push_back(Args[I].getArgument());
3595 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3596 ArgCopy.size(),
3597 ArgCopy.data());
3598}
3599
3600QualType
3601ASTContext::getDependentTemplateSpecializationType(
3602 ElaboratedTypeKeyword Keyword,
3603 NestedNameSpecifier *NNS,
3604 const IdentifierInfo *Name,
3605 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003606 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003607 assert((!NNS || NNS->isDependent()) &&
3608 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003609
Douglas Gregorc42075a2010-02-04 18:10:26 +00003610 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003611 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3612 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003613
Craig Topper36250ad2014-05-12 05:36:57 +00003614 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003615 DependentTemplateSpecializationType *T
3616 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003617 if (T)
3618 return QualType(T, 0);
3619
John McCallc392f372010-06-11 00:33:02 +00003620 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003621
John McCallc392f372010-06-11 00:33:02 +00003622 ElaboratedTypeKeyword CanonKeyword = Keyword;
3623 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3624
3625 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003626 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003627 for (unsigned I = 0; I != NumArgs; ++I) {
3628 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3629 if (!CanonArgs[I].structurallyEquals(Args[I]))
3630 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003631 }
3632
John McCallc392f372010-06-11 00:33:02 +00003633 QualType Canon;
3634 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3635 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3636 Name, NumArgs,
3637 CanonArgs.data());
3638
3639 // Find the insert position again.
3640 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3641 }
3642
3643 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3644 sizeof(TemplateArgument) * NumArgs),
3645 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003646 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003647 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003648 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003649 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003650 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003651}
3652
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003653QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003654 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003655 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003656 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003657
3658 assert(Pattern->containsUnexpandedParameterPack() &&
3659 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003660 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003661 PackExpansionType *T
3662 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3663 if (T)
3664 return QualType(T, 0);
3665
3666 QualType Canon;
3667 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003668 Canon = getCanonicalType(Pattern);
3669 // The canonical type might not contain an unexpanded parameter pack, if it
3670 // contains an alias template specialization which ignores one of its
3671 // parameters.
3672 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003673 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003674
Richard Smith68eea502012-07-16 00:20:35 +00003675 // Find the insert position again, in case we inserted an element into
3676 // PackExpansionTypes and invalidated our insert position.
3677 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3678 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003679 }
3680
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003681 T = new (*this, TypeAlignment)
3682 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003683 Types.push_back(T);
3684 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003685 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003686}
3687
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003688/// CmpProtocolNames - Comparison predicate for sorting protocols
3689/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003690static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3691 ObjCProtocolDecl *const *RHS) {
3692 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003693}
3694
Craig Topper1f26d5b2016-01-03 19:43:23 +00003695static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3696 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003697
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003698 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3699 return false;
3700
Craig Topper1f26d5b2016-01-03 19:43:23 +00003701 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003702 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003703 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003704 return false;
3705 return true;
3706}
3707
Craig Topper6a8c1512015-10-22 01:56:18 +00003708static void
3709SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003710 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003711 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003712
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003713 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003714 for (ObjCProtocolDecl *&P : Protocols)
3715 P = P->getCanonicalDecl();
3716
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003717 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003718 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3719 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003720}
3721
John McCall8b07ec22010-05-15 11:32:37 +00003722QualType ASTContext::getObjCObjectType(QualType BaseType,
3723 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003724 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003725 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003726 llvm::makeArrayRef(Protocols, NumProtocols),
3727 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003728}
3729
3730QualType ASTContext::getObjCObjectType(
3731 QualType baseType,
3732 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003733 ArrayRef<ObjCProtocolDecl *> protocols,
3734 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003735 // If the base type is an interface and there aren't any protocols or
3736 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00003737 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3738 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00003739 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00003740
3741 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003742 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00003743 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00003744 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003745 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3746 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003747
Douglas Gregore9d95f12015-07-07 03:57:35 +00003748 // Determine the type arguments to be used for canonicalization,
3749 // which may be explicitly specified here or written on the base
3750 // type.
3751 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3752 if (effectiveTypeArgs.empty()) {
3753 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3754 effectiveTypeArgs = baseObject->getTypeArgs();
3755 }
John McCallfc93cf92009-10-22 22:37:11 +00003756
Douglas Gregore9d95f12015-07-07 03:57:35 +00003757 // Build the canonical type, which has the canonical base type and a
3758 // sorted-and-uniqued list of protocols and the type arguments
3759 // canonicalized.
3760 QualType canonical;
3761 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3762 effectiveTypeArgs.end(),
3763 [&](QualType type) {
3764 return type.isCanonical();
3765 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00003766 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003767 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3768 // Determine the canonical type arguments.
3769 ArrayRef<QualType> canonTypeArgs;
3770 SmallVector<QualType, 4> canonTypeArgsVec;
3771 if (!typeArgsAreCanonical) {
3772 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3773 for (auto typeArg : effectiveTypeArgs)
3774 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3775 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00003776 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003777 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00003778 }
3779
Douglas Gregore9d95f12015-07-07 03:57:35 +00003780 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3781 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3782 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00003783 canonProtocolsVec.append(protocols.begin(), protocols.end());
3784 SortAndUniqueProtocols(canonProtocolsVec);
3785 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00003786 } else {
3787 canonProtocols = protocols;
3788 }
3789
3790 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003791 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003792
John McCallfc93cf92009-10-22 22:37:11 +00003793 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003794 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3795 }
3796
Douglas Gregore9d95f12015-07-07 03:57:35 +00003797 unsigned size = sizeof(ObjCObjectTypeImpl);
3798 size += typeArgs.size() * sizeof(QualType);
3799 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3800 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00003801 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00003802 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3803 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00003804
3805 Types.push_back(T);
3806 ObjCObjectTypes.InsertNode(T, InsertPos);
3807 return QualType(T, 0);
3808}
3809
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003810/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3811/// protocol list adopt all protocols in QT's qualified-id protocol
3812/// list.
3813bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3814 ObjCInterfaceDecl *IC) {
3815 if (!QT->isObjCQualifiedIdType())
3816 return false;
3817
3818 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3819 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00003820 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003821 if (!IC->ClassImplementsProtocol(Proto, false))
3822 return false;
3823 }
3824 return true;
3825 }
3826 return false;
3827}
3828
3829/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3830/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3831/// of protocols.
3832bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3833 ObjCInterfaceDecl *IDecl) {
3834 if (!QT->isObjCQualifiedIdType())
3835 return false;
3836 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3837 if (!OPT)
3838 return false;
3839 if (!IDecl->hasDefinition())
3840 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003841 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3842 CollectInheritedProtocols(IDecl, InheritedProtocols);
3843 if (InheritedProtocols.empty())
3844 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003845 // Check that if every protocol in list of id<plist> conforms to a protcol
3846 // of IDecl's, then bridge casting is ok.
3847 bool Conforms = false;
3848 for (auto *Proto : OPT->quals()) {
3849 Conforms = false;
3850 for (auto *PI : InheritedProtocols) {
3851 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3852 Conforms = true;
3853 break;
3854 }
3855 }
3856 if (!Conforms)
3857 break;
3858 }
3859 if (Conforms)
3860 return true;
3861
Aaron Ballman83731462014-03-17 16:14:00 +00003862 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003863 // If both the right and left sides have qualifiers.
3864 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00003865 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00003866 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00003867 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003868 break;
3869 }
3870 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003871 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003872 }
3873 return true;
3874}
3875
John McCall8b07ec22010-05-15 11:32:37 +00003876/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3877/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003878QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003879 llvm::FoldingSetNodeID ID;
3880 ObjCObjectPointerType::Profile(ID, ObjectT);
3881
Craig Topper36250ad2014-05-12 05:36:57 +00003882 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00003883 if (ObjCObjectPointerType *QT =
3884 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3885 return QualType(QT, 0);
3886
3887 // Find the canonical object type.
3888 QualType Canonical;
3889 if (!ObjectT.isCanonical()) {
3890 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3891
3892 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003893 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3894 }
3895
Douglas Gregorf85bee62010-02-08 22:59:26 +00003896 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003897 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3898 ObjCObjectPointerType *QType =
3899 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003900
Steve Narofffb4330f2009-06-17 22:40:22 +00003901 Types.push_back(QType);
3902 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003903 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003904}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003905
Douglas Gregor1c283312010-08-11 12:19:30 +00003906/// getObjCInterfaceType - Return the unique reference to the type for the
3907/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003908QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3909 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003910 if (Decl->TypeForDecl)
3911 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003912
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003913 if (PrevDecl) {
3914 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3915 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3916 return QualType(PrevDecl->TypeForDecl, 0);
3917 }
3918
Douglas Gregor7671e532011-12-16 16:34:57 +00003919 // Prefer the definition, if there is one.
3920 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3921 Decl = Def;
3922
Douglas Gregor1c283312010-08-11 12:19:30 +00003923 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3924 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3925 Decl->TypeForDecl = T;
3926 Types.push_back(T);
3927 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003928}
3929
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003930/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3931/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003932/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003933/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003934/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003935QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003936 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003937 if (tofExpr->isTypeDependent()) {
3938 llvm::FoldingSetNodeID ID;
3939 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003940
Craig Topper36250ad2014-05-12 05:36:57 +00003941 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003942 DependentTypeOfExprType *Canon
3943 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3944 if (Canon) {
3945 // We already have a "canonical" version of an identical, dependent
3946 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003947 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003948 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003949 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003950 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003951 Canon
3952 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003953 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3954 toe = Canon;
3955 }
3956 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003957 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003958 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003959 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003960 Types.push_back(toe);
3961 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003962}
3963
Steve Naroffa773cd52007-08-01 18:02:17 +00003964/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00003965/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00003966/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00003967/// an issue. This doesn't affect the type checker, since it operates
3968/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003969QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003970 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003971 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003972 Types.push_back(tot);
3973 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003974}
3975
Richard Smith8eb1d322014-06-05 20:13:13 +00003976/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3977/// nodes. This would never be helpful, since each such type has its own
3978/// expression, and would not give a significant memory saving, since there
3979/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00003980QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003981 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00003982
3983 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00003984 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00003985 // unique dependent type. Two such decltype-specifiers refer to the same
3986 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00003987 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003988 llvm::FoldingSetNodeID ID;
3989 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003990
Craig Topper36250ad2014-05-12 05:36:57 +00003991 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00003992 DependentDecltypeType *Canon
3993 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00003994 if (!Canon) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003995 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003996 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003997 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003998 }
Richard Smith8eb1d322014-06-05 20:13:13 +00003999 dt = new (*this, TypeAlignment)
4000 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004001 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004002 dt = new (*this, TypeAlignment)
4003 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004004 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004005 Types.push_back(dt);
4006 return QualType(dt, 0);
4007}
4008
Alexis Hunte852b102011-05-24 22:41:36 +00004009/// getUnaryTransformationType - We don't unique these, since the memory
4010/// savings are minimal and these are rare.
4011QualType ASTContext::getUnaryTransformType(QualType BaseType,
4012 QualType UnderlyingType,
4013 UnaryTransformType::UTTKind Kind)
4014 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004015 UnaryTransformType *ut = nullptr;
4016
4017 if (BaseType->isDependentType()) {
4018 // Look in the folding set for an existing type.
4019 llvm::FoldingSetNodeID ID;
4020 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4021
4022 void *InsertPos = nullptr;
4023 DependentUnaryTransformType *Canon
4024 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4025
4026 if (!Canon) {
4027 // Build a new, canonical __underlying_type(type) type.
4028 Canon = new (*this, TypeAlignment)
4029 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4030 Kind);
4031 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4032 }
4033 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4034 QualType(), Kind,
4035 QualType(Canon, 0));
4036 } else {
4037 QualType CanonType = getCanonicalType(UnderlyingType);
4038 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4039 UnderlyingType, Kind,
4040 CanonType);
4041 }
4042 Types.push_back(ut);
4043 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004044}
4045
Richard Smith2a7d4812013-05-04 07:00:32 +00004046/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4047/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4048/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004049QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004050 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004051 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004052 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004053
Richard Smith2a7d4812013-05-04 07:00:32 +00004054 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004055 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004056 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004057 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004058 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4059 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004060
Richard Smith74aeef52013-04-26 16:15:35 +00004061 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004062 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004063 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004064 Types.push_back(AT);
4065 if (InsertPos)
4066 AutoTypes.InsertNode(AT, InsertPos);
4067 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004068}
4069
Eli Friedman0dfb8892011-10-06 23:00:33 +00004070/// getAtomicType - Return the uniqued reference to the atomic type for
4071/// the given value type.
4072QualType ASTContext::getAtomicType(QualType T) const {
4073 // Unique pointers, to guarantee there is only one pointer of a particular
4074 // structure.
4075 llvm::FoldingSetNodeID ID;
4076 AtomicType::Profile(ID, T);
4077
Craig Topper36250ad2014-05-12 05:36:57 +00004078 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004079 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4080 return QualType(AT, 0);
4081
4082 // If the atomic value type isn't canonical, this won't be a canonical type
4083 // either, so fill in the canonical type field.
4084 QualType Canonical;
4085 if (!T.isCanonical()) {
4086 Canonical = getAtomicType(getCanonicalType(T));
4087
4088 // Get the new insert position for the node we care about.
4089 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004090 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004091 }
4092 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4093 Types.push_back(New);
4094 AtomicTypes.InsertNode(New, InsertPos);
4095 return QualType(New, 0);
4096}
4097
Richard Smith02e85f32011-04-14 22:09:26 +00004098/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4099QualType ASTContext::getAutoDeductType() const {
4100 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004101 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004102 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004103 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004104 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004105 return AutoDeductTy;
4106}
4107
4108/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4109QualType ASTContext::getAutoRRefDeductType() const {
4110 if (AutoRRefDeductTy.isNull())
4111 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4112 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4113 return AutoRRefDeductTy;
4114}
4115
Chris Lattnerfb072462007-01-23 05:45:31 +00004116/// getTagDeclType - Return the unique reference to the type for the
4117/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004118QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004119 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004120 // FIXME: What is the design on getTagDeclType when it requires casting
4121 // away const? mutable?
4122 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004123}
4124
Mike Stump11289f42009-09-09 15:08:12 +00004125/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4126/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4127/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004128CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004129 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004130}
Chris Lattnerfb072462007-01-23 05:45:31 +00004131
Hans Wennborg27541db2011-10-27 08:29:09 +00004132/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4133CanQualType ASTContext::getIntMaxType() const {
4134 return getFromTargetType(Target->getIntMaxType());
4135}
4136
4137/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4138CanQualType ASTContext::getUIntMaxType() const {
4139 return getFromTargetType(Target->getUIntMaxType());
4140}
4141
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004142/// getSignedWCharType - Return the type of "signed wchar_t".
4143/// Used when in C++, as a GCC extension.
4144QualType ASTContext::getSignedWCharType() const {
4145 // FIXME: derive from "Target" ?
4146 return WCharTy;
4147}
4148
4149/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4150/// Used when in C++, as a GCC extension.
4151QualType ASTContext::getUnsignedWCharType() const {
4152 // FIXME: derive from "Target" ?
4153 return UnsignedIntTy;
4154}
4155
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004156QualType ASTContext::getIntPtrType() const {
4157 return getFromTargetType(Target->getIntPtrType());
4158}
4159
4160QualType ASTContext::getUIntPtrType() const {
4161 return getCorrespondingUnsignedType(getIntPtrType());
4162}
4163
Hans Wennborg27541db2011-10-27 08:29:09 +00004164/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004165/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4166QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004167 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004168}
4169
Eli Friedman4e91899e2012-11-27 02:58:24 +00004170/// \brief Return the unique type for "pid_t" defined in
4171/// <sys/types.h>. We need this to compute the correct type for vfork().
4172QualType ASTContext::getProcessIDType() const {
4173 return getFromTargetType(Target->getProcessIDType());
4174}
4175
Chris Lattnera21ad802008-04-02 05:18:44 +00004176//===----------------------------------------------------------------------===//
4177// Type Operators
4178//===----------------------------------------------------------------------===//
4179
Jay Foad39c79802011-01-12 09:06:06 +00004180CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004181 // Push qualifiers into arrays, and then discard any remaining
4182 // qualifiers.
4183 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004184 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004185 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004186 QualType Result;
4187 if (isa<ArrayType>(Ty)) {
4188 Result = getArrayDecayedType(QualType(Ty,0));
4189 } else if (isa<FunctionType>(Ty)) {
4190 Result = getPointerType(QualType(Ty, 0));
4191 } else {
4192 Result = QualType(Ty, 0);
4193 }
4194
4195 return CanQualType::CreateUnsafe(Result);
4196}
4197
John McCall6c9dd522011-01-18 07:41:22 +00004198QualType ASTContext::getUnqualifiedArrayType(QualType type,
4199 Qualifiers &quals) {
4200 SplitQualType splitType = type.getSplitUnqualifiedType();
4201
4202 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4203 // the unqualified desugared type and then drops it on the floor.
4204 // We then have to strip that sugar back off with
4205 // getUnqualifiedDesugaredType(), which is silly.
4206 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004207 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004208
4209 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004210 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004211 quals = splitType.Quals;
4212 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004213 }
4214
John McCall6c9dd522011-01-18 07:41:22 +00004215 // Otherwise, recurse on the array's element type.
4216 QualType elementType = AT->getElementType();
4217 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4218
4219 // If that didn't change the element type, AT has no qualifiers, so we
4220 // can just use the results in splitType.
4221 if (elementType == unqualElementType) {
4222 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004223 quals = splitType.Quals;
4224 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004225 }
4226
4227 // Otherwise, add in the qualifiers from the outermost type, then
4228 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004229 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004230
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004231 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004232 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004233 CAT->getSizeModifier(), 0);
4234 }
4235
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004236 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004237 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004238 }
4239
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004240 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004241 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004242 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004243 VAT->getSizeModifier(),
4244 VAT->getIndexTypeCVRQualifiers(),
4245 VAT->getBracketsRange());
4246 }
4247
4248 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004249 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004250 DSAT->getSizeModifier(), 0,
4251 SourceRange());
4252}
4253
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004254/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4255/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4256/// they point to and return true. If T1 and T2 aren't pointer types
4257/// or pointer-to-member types, or if they are not similar at this
4258/// level, returns false and leaves T1 and T2 unchanged. Top-level
4259/// qualifiers on T1 and T2 are ignored. This function will typically
4260/// be called in a loop that successively "unwraps" pointer and
4261/// pointer-to-member types to compare them at each level.
4262bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4263 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4264 *T2PtrType = T2->getAs<PointerType>();
4265 if (T1PtrType && T2PtrType) {
4266 T1 = T1PtrType->getPointeeType();
4267 T2 = T2PtrType->getPointeeType();
4268 return true;
4269 }
4270
4271 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4272 *T2MPType = T2->getAs<MemberPointerType>();
4273 if (T1MPType && T2MPType &&
4274 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4275 QualType(T2MPType->getClass(), 0))) {
4276 T1 = T1MPType->getPointeeType();
4277 T2 = T2MPType->getPointeeType();
4278 return true;
4279 }
4280
David Blaikiebbafb8a2012-03-11 07:00:24 +00004281 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004282 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4283 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4284 if (T1OPType && T2OPType) {
4285 T1 = T1OPType->getPointeeType();
4286 T2 = T2OPType->getPointeeType();
4287 return true;
4288 }
4289 }
4290
4291 // FIXME: Block pointers, too?
4292
4293 return false;
4294}
4295
Jay Foad39c79802011-01-12 09:06:06 +00004296DeclarationNameInfo
4297ASTContext::getNameForTemplate(TemplateName Name,
4298 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004299 switch (Name.getKind()) {
4300 case TemplateName::QualifiedTemplate:
4301 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004302 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004303 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4304 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004305
John McCalld9dfe3a2011-06-30 08:33:18 +00004306 case TemplateName::OverloadedTemplate: {
4307 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4308 // DNInfo work in progress: CHECKME: what about DNLoc?
4309 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4310 }
4311
4312 case TemplateName::DependentTemplate: {
4313 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004314 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004315 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004316 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4317 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004318 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004319 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4320 // DNInfo work in progress: FIXME: source locations?
4321 DeclarationNameLoc DNLoc;
4322 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4323 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4324 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004325 }
4326 }
4327
John McCalld9dfe3a2011-06-30 08:33:18 +00004328 case TemplateName::SubstTemplateTemplateParm: {
4329 SubstTemplateTemplateParmStorage *subst
4330 = Name.getAsSubstTemplateTemplateParm();
4331 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4332 NameLoc);
4333 }
4334
4335 case TemplateName::SubstTemplateTemplateParmPack: {
4336 SubstTemplateTemplateParmPackStorage *subst
4337 = Name.getAsSubstTemplateTemplateParmPack();
4338 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4339 NameLoc);
4340 }
4341 }
4342
4343 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004344}
4345
Jay Foad39c79802011-01-12 09:06:06 +00004346TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004347 switch (Name.getKind()) {
4348 case TemplateName::QualifiedTemplate:
4349 case TemplateName::Template: {
4350 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004351 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004352 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004353 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4354
4355 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004356 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004357 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004358
John McCalld9dfe3a2011-06-30 08:33:18 +00004359 case TemplateName::OverloadedTemplate:
4360 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004361
John McCalld9dfe3a2011-06-30 08:33:18 +00004362 case TemplateName::DependentTemplate: {
4363 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4364 assert(DTN && "Non-dependent template names must refer to template decls.");
4365 return DTN->CanonicalTemplateName;
4366 }
4367
4368 case TemplateName::SubstTemplateTemplateParm: {
4369 SubstTemplateTemplateParmStorage *subst
4370 = Name.getAsSubstTemplateTemplateParm();
4371 return getCanonicalTemplateName(subst->getReplacement());
4372 }
4373
4374 case TemplateName::SubstTemplateTemplateParmPack: {
4375 SubstTemplateTemplateParmPackStorage *subst
4376 = Name.getAsSubstTemplateTemplateParmPack();
4377 TemplateTemplateParmDecl *canonParameter
4378 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4379 TemplateArgument canonArgPack
4380 = getCanonicalTemplateArgument(subst->getArgumentPack());
4381 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4382 }
4383 }
4384
4385 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004386}
4387
Douglas Gregoradee3e32009-11-11 23:06:43 +00004388bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4389 X = getCanonicalTemplateName(X);
4390 Y = getCanonicalTemplateName(Y);
4391 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4392}
4393
Mike Stump11289f42009-09-09 15:08:12 +00004394TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004395ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004396 switch (Arg.getKind()) {
4397 case TemplateArgument::Null:
4398 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004399
Douglas Gregora8e02e72009-07-28 23:00:59 +00004400 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004401 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004402
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004403 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004404 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004405 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004406 }
Mike Stump11289f42009-09-09 15:08:12 +00004407
Eli Friedmanb826a002012-09-26 02:36:12 +00004408 case TemplateArgument::NullPtr:
4409 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4410 /*isNullPtr*/true);
4411
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004412 case TemplateArgument::Template:
4413 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004414
4415 case TemplateArgument::TemplateExpansion:
4416 return TemplateArgument(getCanonicalTemplateName(
4417 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004418 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004419
Douglas Gregora8e02e72009-07-28 23:00:59 +00004420 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004421 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004422
Douglas Gregora8e02e72009-07-28 23:00:59 +00004423 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004424 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004425
Douglas Gregora8e02e72009-07-28 23:00:59 +00004426 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004427 if (Arg.pack_size() == 0)
4428 return Arg;
4429
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004430 TemplateArgument *CanonArgs
4431 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004432 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004433 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004434 AEnd = Arg.pack_end();
4435 A != AEnd; (void)++A, ++Idx)
4436 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004437
Benjamin Kramercce63472015-08-05 09:40:22 +00004438 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004439 }
4440 }
4441
4442 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004443 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004444}
4445
Douglas Gregor333489b2009-03-27 23:10:48 +00004446NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004447ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004448 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004449 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004450
4451 switch (NNS->getKind()) {
4452 case NestedNameSpecifier::Identifier:
4453 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004454 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004455 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4456 NNS->getAsIdentifier());
4457
4458 case NestedNameSpecifier::Namespace:
4459 // A namespace is canonical; build a nested-name-specifier with
4460 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004461 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004462 NNS->getAsNamespace()->getOriginalNamespace());
4463
4464 case NestedNameSpecifier::NamespaceAlias:
4465 // A namespace is canonical; build a nested-name-specifier with
4466 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004467 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004468 NNS->getAsNamespaceAlias()->getNamespace()
4469 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004470
4471 case NestedNameSpecifier::TypeSpec:
4472 case NestedNameSpecifier::TypeSpecWithTemplate: {
4473 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004474
4475 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4476 // break it apart into its prefix and identifier, then reconsititute those
4477 // as the canonical nested-name-specifier. This is required to canonicalize
4478 // a dependent nested-name-specifier involving typedefs of dependent-name
4479 // types, e.g.,
4480 // typedef typename T::type T1;
4481 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004482 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4483 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004484 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004485
Eli Friedman5358a0a2012-03-03 04:09:56 +00004486 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4487 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4488 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004489 return NestedNameSpecifier::Create(*this, nullptr, false,
4490 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004491 }
4492
4493 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004494 case NestedNameSpecifier::Super:
4495 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004496 return NNS;
4497 }
4498
David Blaikie8a40f702012-01-17 06:56:22 +00004499 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004500}
4501
Jay Foad39c79802011-01-12 09:06:06 +00004502const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004503 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004504 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004505 // Handle the common positive case fast.
4506 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4507 return AT;
4508 }
Mike Stump11289f42009-09-09 15:08:12 +00004509
John McCall8ccfcb52009-09-24 19:53:00 +00004510 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004511 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004512 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004513
John McCall8ccfcb52009-09-24 19:53:00 +00004514 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004515 // implements C99 6.7.3p8: "If the specification of an array type includes
4516 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004517
Chris Lattner7adf0762008-08-04 07:31:14 +00004518 // If we get here, we either have type qualifiers on the type, or we have
4519 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004520 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004521
John McCall33ddac02011-01-19 10:06:00 +00004522 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004523 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004524
Chris Lattner7adf0762008-08-04 07:31:14 +00004525 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004526 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004527 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004528 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004529
Chris Lattner7adf0762008-08-04 07:31:14 +00004530 // Otherwise, we have an array and we have qualifiers on it. Push the
4531 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004532 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004533
Chris Lattner7adf0762008-08-04 07:31:14 +00004534 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4535 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4536 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004537 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004538 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4539 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4540 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004541 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004542
Mike Stump11289f42009-09-09 15:08:12 +00004543 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004544 = dyn_cast<DependentSizedArrayType>(ATy))
4545 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004546 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004547 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004548 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004549 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004550 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004551
Chris Lattner7adf0762008-08-04 07:31:14 +00004552 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004553 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004554 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004555 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004556 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004557 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004558}
4559
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004560QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004561 if (T->isArrayType() || T->isFunctionType())
4562 return getDecayedType(T);
4563 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004564}
4565
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004566QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004567 T = getVariableArrayDecayedType(T);
4568 T = getAdjustedParameterType(T);
4569 return T.getUnqualifiedType();
4570}
4571
David Majnemerd09a51c2015-03-03 01:50:05 +00004572QualType ASTContext::getExceptionObjectType(QualType T) const {
4573 // C++ [except.throw]p3:
4574 // A throw-expression initializes a temporary object, called the exception
4575 // object, the type of which is determined by removing any top-level
4576 // cv-qualifiers from the static type of the operand of throw and adjusting
4577 // the type from "array of T" or "function returning T" to "pointer to T"
4578 // or "pointer to function returning T", [...]
4579 T = getVariableArrayDecayedType(T);
4580 if (T->isArrayType() || T->isFunctionType())
4581 T = getDecayedType(T);
4582 return T.getUnqualifiedType();
4583}
4584
Chris Lattnera21ad802008-04-02 05:18:44 +00004585/// getArrayDecayedType - Return the properly qualified result of decaying the
4586/// specified array type to a pointer. This operation is non-trivial when
4587/// handling typedefs etc. The canonical type of "T" must be an array type,
4588/// this returns a pointer to a properly qualified element of the array.
4589///
4590/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004591QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004592 // Get the element type with 'getAsArrayType' so that we don't lose any
4593 // typedefs in the element type of the array. This also handles propagation
4594 // of type qualifiers from the array type into the element type if present
4595 // (C99 6.7.3p8).
4596 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4597 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004598
Chris Lattner7adf0762008-08-04 07:31:14 +00004599 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004600
4601 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004602 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004603}
4604
John McCall33ddac02011-01-19 10:06:00 +00004605QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4606 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004607}
4608
John McCall33ddac02011-01-19 10:06:00 +00004609QualType ASTContext::getBaseElementType(QualType type) const {
4610 Qualifiers qs;
4611 while (true) {
4612 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004613 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004614 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004615
John McCall33ddac02011-01-19 10:06:00 +00004616 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004617 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004618 }
Mike Stump11289f42009-09-09 15:08:12 +00004619
John McCall33ddac02011-01-19 10:06:00 +00004620 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004621}
4622
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004623/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004624uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004625ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4626 uint64_t ElementCount = 1;
4627 do {
4628 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004629 CA = dyn_cast_or_null<ConstantArrayType>(
4630 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004631 } while (CA);
4632 return ElementCount;
4633}
4634
Steve Naroff0af91202007-04-27 21:51:21 +00004635/// getFloatingRank - Return a relative rank for floating point types.
4636/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004637static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004638 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004639 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004640
John McCall9dd450b2009-09-21 23:43:11 +00004641 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4642 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004643 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004644 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004645 case BuiltinType::Float: return FloatRank;
4646 case BuiltinType::Double: return DoubleRank;
4647 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004648 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00004649 }
4650}
4651
Mike Stump11289f42009-09-09 15:08:12 +00004652/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4653/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004654/// 'typeDomain' is a real floating point or complex type.
4655/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004656QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4657 QualType Domain) const {
4658 FloatingRank EltRank = getFloatingRank(Size);
4659 if (Domain->isComplexType()) {
4660 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004661 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004662 case FloatRank: return FloatComplexTy;
4663 case DoubleRank: return DoubleComplexTy;
4664 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004665 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004666 }
Steve Naroff0af91202007-04-27 21:51:21 +00004667 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004668
4669 assert(Domain->isRealFloatingType() && "Unknown domain!");
4670 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004671 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004672 case FloatRank: return FloatTy;
4673 case DoubleRank: return DoubleTy;
4674 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00004675 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00004676 }
David Blaikief47fa302012-01-17 02:30:50 +00004677 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004678}
4679
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004680/// getFloatingTypeOrder - Compare the rank of the two specified floating
4681/// point types, ignoring the domain of the type (i.e. 'double' ==
4682/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004683/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004684int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004685 FloatingRank LHSR = getFloatingRank(LHS);
4686 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004687
Chris Lattnerb90739d2008-04-06 23:38:49 +00004688 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004689 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004690 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004691 return 1;
4692 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004693}
4694
Chris Lattner76a00cf2008-04-06 22:59:24 +00004695/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4696/// routine will assert if passed a built-in type that isn't an integer or enum,
4697/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004698unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004699 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004700
Chris Lattner76a00cf2008-04-06 22:59:24 +00004701 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004702 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004703 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004704 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004705 case BuiltinType::Char_S:
4706 case BuiltinType::Char_U:
4707 case BuiltinType::SChar:
4708 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004709 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004710 case BuiltinType::Short:
4711 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004712 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004713 case BuiltinType::Int:
4714 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004715 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004716 case BuiltinType::Long:
4717 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004718 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004719 case BuiltinType::LongLong:
4720 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004721 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004722 case BuiltinType::Int128:
4723 case BuiltinType::UInt128:
4724 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004725 }
4726}
4727
Eli Friedman629ffb92009-08-20 04:21:42 +00004728/// \brief Whether this is a promotable bitfield reference according
4729/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4730///
4731/// \returns the type this bit-field will promote to, or NULL if no
4732/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004733QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004734 if (E->isTypeDependent() || E->isValueDependent())
4735 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00004736
4737 // FIXME: We should not do this unless E->refersToBitField() is true. This
4738 // matters in C where getSourceBitField() will find bit-fields for various
4739 // cases where the source expression is not a bit-field designator.
4740
John McCalld25db7e2013-05-06 21:39:12 +00004741 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004742 if (!Field)
4743 return QualType();
4744
4745 QualType FT = Field->getType();
4746
Richard Smithcaf33902011-10-10 18:28:20 +00004747 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004748 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00004749 // C++ [conv.prom]p5:
4750 // A prvalue for an integral bit-field can be converted to a prvalue of type
4751 // int if int can represent all the values of the bit-field; otherwise, it
4752 // can be converted to unsigned int if unsigned int can represent all the
4753 // values of the bit-field. If the bit-field is larger yet, no integral
4754 // promotion applies to it.
4755 // C11 6.3.1.1/2:
4756 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4757 // If an int can represent all values of the original type (as restricted by
4758 // the width, for a bit-field), the value is converted to an int; otherwise,
4759 // it is converted to an unsigned int.
4760 //
4761 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4762 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00004763 if (BitWidth < IntSize)
4764 return IntTy;
4765
4766 if (BitWidth == IntSize)
4767 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4768
4769 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00004770 // like the base type. GCC has some weird bugs in this area that we
4771 // deliberately do not follow (GCC follows a pre-standard resolution to
4772 // C's DR315 which treats bit-width as being part of the type, and this leaks
4773 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00004774 return QualType();
4775}
4776
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004777/// getPromotedIntegerType - Returns the type that Promotable will
4778/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4779/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004780QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004781 assert(!Promotable.isNull());
4782 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004783 if (const EnumType *ET = Promotable->getAs<EnumType>())
4784 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004785
4786 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4787 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4788 // (3.9.1) can be converted to a prvalue of the first of the following
4789 // types that can represent all the values of its underlying type:
4790 // int, unsigned int, long int, unsigned long int, long long int, or
4791 // unsigned long long int [...]
4792 // FIXME: Is there some better way to compute this?
4793 if (BT->getKind() == BuiltinType::WChar_S ||
4794 BT->getKind() == BuiltinType::WChar_U ||
4795 BT->getKind() == BuiltinType::Char16 ||
4796 BT->getKind() == BuiltinType::Char32) {
4797 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4798 uint64_t FromSize = getTypeSize(BT);
4799 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4800 LongLongTy, UnsignedLongLongTy };
4801 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4802 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4803 if (FromSize < ToSize ||
4804 (FromSize == ToSize &&
4805 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4806 return PromoteTypes[Idx];
4807 }
4808 llvm_unreachable("char type should fit into long long");
4809 }
4810 }
4811
4812 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004813 if (Promotable->isSignedIntegerType())
4814 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004815 uint64_t PromotableSize = getIntWidth(Promotable);
4816 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004817 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4818 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4819}
4820
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004821/// \brief Recurses in pointer/array types until it finds an objc retainable
4822/// type and returns its ownership.
4823Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4824 while (!T.isNull()) {
4825 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4826 return T.getObjCLifetime();
4827 if (T->isArrayType())
4828 T = getBaseElementType(T);
4829 else if (const PointerType *PT = T->getAs<PointerType>())
4830 T = PT->getPointeeType();
4831 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004832 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004833 else
4834 break;
4835 }
4836
4837 return Qualifiers::OCL_None;
4838}
4839
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004840static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4841 // Incomplete enum types are not treated as integer types.
4842 // FIXME: In C++, enum types are never integer types.
4843 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4844 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00004845 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004846}
4847
Mike Stump11289f42009-09-09 15:08:12 +00004848/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004849/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004850/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004851int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004852 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4853 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004854
4855 // Unwrap enums to their underlying type.
4856 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4857 LHSC = getIntegerTypeForEnum(ET);
4858 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4859 RHSC = getIntegerTypeForEnum(ET);
4860
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004861 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004862
Chris Lattner76a00cf2008-04-06 22:59:24 +00004863 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4864 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004865
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004866 unsigned LHSRank = getIntegerRank(LHSC);
4867 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004868
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004869 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4870 if (LHSRank == RHSRank) return 0;
4871 return LHSRank > RHSRank ? 1 : -1;
4872 }
Mike Stump11289f42009-09-09 15:08:12 +00004873
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004874 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4875 if (LHSUnsigned) {
4876 // If the unsigned [LHS] type is larger, return it.
4877 if (LHSRank >= RHSRank)
4878 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004879
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004880 // If the signed type can represent all values of the unsigned type, it
4881 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004882 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004883 return -1;
4884 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004885
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004886 // If the unsigned [RHS] type is larger, return it.
4887 if (RHSRank >= LHSRank)
4888 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004889
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004890 // If the signed type can represent all values of the unsigned type, it
4891 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004892 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004893 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004894}
Anders Carlsson98f07902007-08-17 05:31:46 +00004895
Ben Langmuirf5416742016-02-04 00:55:24 +00004896TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004897 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004898 assert(!CFConstantStringTagDecl &&
4899 "tag and typedef should be initialized together");
4900 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
4901 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004902
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004903 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00004904 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00004905
Anders Carlsson98f07902007-08-17 05:31:46 +00004906 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004907 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004908 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004909 // int flags;
4910 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004911 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00004912 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004913 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00004914 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00004915 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004916 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00004917 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00004918
Anders Carlsson98f07902007-08-17 05:31:46 +00004919 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004920 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004921 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004922 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00004923 SourceLocation(),
4924 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00004925 FieldTypes[i], /*TInfo=*/nullptr,
4926 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00004927 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004928 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004929 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00004930 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004931 }
4932
Ben Langmuirf5416742016-02-04 00:55:24 +00004933 CFConstantStringTagDecl->completeDefinition();
4934 // This type is designed to be compatible with NSConstantString, but cannot
4935 // use the same name, since NSConstantString is an interface.
4936 auto tagType = getTagDeclType(CFConstantStringTagDecl);
4937 CFConstantStringTypeDecl =
4938 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00004939 }
Mike Stump11289f42009-09-09 15:08:12 +00004940
Quentin Colombet043406b2016-02-03 22:41:00 +00004941 return CFConstantStringTypeDecl;
4942}
4943
Ben Langmuirf5416742016-02-04 00:55:24 +00004944RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
4945 if (!CFConstantStringTagDecl)
4946 getCFConstantStringDecl(); // Build the tag and the typedef.
4947 return CFConstantStringTagDecl;
4948}
4949
Quentin Colombet043406b2016-02-03 22:41:00 +00004950// getCFConstantStringType - Return the type used for constant CFStrings.
4951QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00004952 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00004953}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004954
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004955QualType ASTContext::getObjCSuperType() const {
4956 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004957 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004958 TUDecl->addDecl(ObjCSuperTypeDecl);
4959 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4960 }
4961 return ObjCSuperType;
4962}
4963
Douglas Gregor512b0772009-04-23 22:29:11 +00004964void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00004965 const TypedefType *TD = T->getAs<TypedefType>();
4966 assert(TD && "Invalid CFConstantStringType");
4967 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
4968 auto TagType =
4969 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
4970 assert(TagType && "Invalid CFConstantStringType");
4971 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00004972}
4973
Jay Foad39c79802011-01-12 09:06:06 +00004974QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004975 if (BlockDescriptorType)
4976 return getTagDeclType(BlockDescriptorType);
4977
Alp Toker2dea15b2013-12-17 01:22:38 +00004978 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004979 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004980 RD = buildImplicitRecord("__block_descriptor");
4981 RD->startDefinition();
4982
Mike Stumpd0153282009-10-20 02:12:22 +00004983 QualType FieldTypes[] = {
4984 UnsignedLongTy,
4985 UnsignedLongTy,
4986 };
4987
Craig Topperd6d31ac2013-07-15 08:24:27 +00004988 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004989 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004990 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004991 };
4992
4993 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004994 FieldDecl *Field = FieldDecl::Create(
4995 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004996 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4997 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004998 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004999 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005000 }
5001
Alp Toker2dea15b2013-12-17 01:22:38 +00005002 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005003
Alp Toker2dea15b2013-12-17 01:22:38 +00005004 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005005
5006 return getTagDeclType(BlockDescriptorType);
5007}
5008
Jay Foad39c79802011-01-12 09:06:06 +00005009QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005010 if (BlockDescriptorExtendedType)
5011 return getTagDeclType(BlockDescriptorExtendedType);
5012
Alp Toker2dea15b2013-12-17 01:22:38 +00005013 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005014 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005015 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5016 RD->startDefinition();
5017
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005018 QualType FieldTypes[] = {
5019 UnsignedLongTy,
5020 UnsignedLongTy,
5021 getPointerType(VoidPtrTy),
5022 getPointerType(VoidPtrTy)
5023 };
5024
Craig Topperd6d31ac2013-07-15 08:24:27 +00005025 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005026 "reserved",
5027 "Size",
5028 "CopyFuncPtr",
5029 "DestroyFuncPtr"
5030 };
5031
5032 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005033 FieldDecl *Field = FieldDecl::Create(
5034 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005035 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5036 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005037 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005038 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005039 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005040 }
5041
Alp Toker2dea15b2013-12-17 01:22:38 +00005042 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005043
Alp Toker2dea15b2013-12-17 01:22:38 +00005044 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005045 return getTagDeclType(BlockDescriptorExtendedType);
5046}
5047
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005048/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5049/// requires copy/dispose. Note that this must match the logic
5050/// in buildByrefHelpers.
5051bool ASTContext::BlockRequiresCopying(QualType Ty,
5052 const VarDecl *D) {
5053 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5054 const Expr *copyExpr = getBlockVarCopyInits(D);
5055 if (!copyExpr && record->hasTrivialDestructor()) return false;
5056
Mike Stump94967902009-10-21 18:16:27 +00005057 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005058 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005059
5060 if (!Ty->isObjCRetainableType()) return false;
5061
5062 Qualifiers qs = Ty.getQualifiers();
5063
5064 // If we have lifetime, that dominates.
5065 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005066 switch (lifetime) {
5067 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5068
5069 // These are just bits as far as the runtime is concerned.
5070 case Qualifiers::OCL_ExplicitNone:
5071 case Qualifiers::OCL_Autoreleasing:
5072 return false;
5073
5074 // Tell the runtime that this is ARC __weak, called by the
5075 // byref routines.
5076 case Qualifiers::OCL_Weak:
5077 // ARC __strong __block variables need to be retained.
5078 case Qualifiers::OCL_Strong:
5079 return true;
5080 }
5081 llvm_unreachable("fell out of lifetime switch!");
5082 }
5083 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5084 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005085}
5086
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005087bool ASTContext::getByrefLifetime(QualType Ty,
5088 Qualifiers::ObjCLifetime &LifeTime,
5089 bool &HasByrefExtendedLayout) const {
5090
5091 if (!getLangOpts().ObjC1 ||
5092 getLangOpts().getGC() != LangOptions::NonGC)
5093 return false;
5094
5095 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005096 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005097 HasByrefExtendedLayout = true;
5098 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005099 } else if ((LifeTime = Ty.getObjCLifetime())) {
5100 // Honor the ARC qualifiers.
5101 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5102 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005103 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005104 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005105 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005106 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005107 return true;
5108}
5109
Douglas Gregorbab8a962011-09-08 01:46:34 +00005110TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5111 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005112 ObjCInstanceTypeDecl =
5113 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005114 return ObjCInstanceTypeDecl;
5115}
5116
Anders Carlsson18acd442007-10-29 06:33:42 +00005117// This returns true if a type has been typedefed to BOOL:
5118// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005119static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005120 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005121 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5122 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005123
Anders Carlssond8499822007-10-29 05:01:08 +00005124 return false;
5125}
5126
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005127/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005128/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005129CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005130 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5131 return CharUnits::Zero();
5132
Ken Dyck40775002010-01-11 17:06:35 +00005133 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005134
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005135 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005136 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005137 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005138 // Treat arrays as pointers, since that's how they're passed in.
5139 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005140 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005141 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005142}
5143
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005144bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005145 return getTargetInfo().getCXXABI().isMicrosoft() &&
5146 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005147 VD->getType()->isIntegralOrEnumerationType() &&
5148 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005149}
5150
Richard Smithd9b90092016-07-02 01:32:16 +00005151ASTContext::InlineVariableDefinitionKind
5152ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5153 if (!VD->isInline())
5154 return InlineVariableDefinitionKind::None;
5155
5156 // In almost all cases, it's a weak definition.
5157 auto *First = VD->getFirstDecl();
5158 if (!First->isConstexpr() || First->isInlineSpecified() ||
5159 !VD->isStaticDataMember())
5160 return InlineVariableDefinitionKind::Weak;
5161
5162 // If there's a file-context declaration in this translation unit, it's a
5163 // non-discardable definition.
5164 for (auto *D : VD->redecls())
5165 if (D->getLexicalDeclContext()->isFileContext())
5166 return InlineVariableDefinitionKind::Strong;
5167
5168 // If we've not seen one yet, we don't know.
5169 return InlineVariableDefinitionKind::WeakUnknown;
5170}
5171
Ken Dyck40775002010-01-11 17:06:35 +00005172static inline
5173std::string charUnitsToString(const CharUnits &CU) {
5174 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005175}
5176
John McCall351762c2011-02-07 10:33:21 +00005177/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005178/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005179std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5180 std::string S;
5181
David Chisnall950a9512009-11-17 19:33:30 +00005182 const BlockDecl *Decl = Expr->getBlockDecl();
5183 QualType BlockTy =
5184 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5185 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005186 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005187 getObjCEncodingForMethodParameter(
5188 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5189 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005190 else
Alp Toker314cc812014-01-25 16:55:45 +00005191 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005192 // Compute size of all parameters.
5193 // Start with computing size of a pointer in number of bytes.
5194 // FIXME: There might(should) be a better way of doing this computation!
5195 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005196 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5197 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005198 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005199 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005200 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005201 if (sz.isZero())
5202 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005203 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005204 ParmOffset += sz;
5205 }
5206 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005207 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005208 // Block pointer and offset.
5209 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005210
5211 // Argument types.
5212 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005213 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005214 QualType PType = PVDecl->getOriginalType();
5215 if (const ArrayType *AT =
5216 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5217 // Use array's original type only if it has known number of
5218 // elements.
5219 if (!isa<ConstantArrayType>(AT))
5220 PType = PVDecl->getType();
5221 } else if (PType->isFunctionType())
5222 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005223 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005224 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5225 S, true /*Extended*/);
5226 else
5227 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005228 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005229 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005230 }
John McCall351762c2011-02-07 10:33:21 +00005231
5232 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005233}
5234
Douglas Gregora9d84932011-05-27 01:19:52 +00005235bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00005236 std::string& S) {
5237 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005238 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005239 CharUnits ParmOffset;
5240 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005241 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005242 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005243 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005244 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005245 continue;
5246
David Chisnall50e4eba2010-12-30 14:05:53 +00005247 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00005248 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005249 ParmOffset += sz;
5250 }
5251 S += charUnitsToString(ParmOffset);
5252 ParmOffset = CharUnits::Zero();
5253
5254 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005255 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005256 QualType PType = PVDecl->getOriginalType();
5257 if (const ArrayType *AT =
5258 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5259 // Use array's original type only if it has known number of
5260 // elements.
5261 if (!isa<ConstantArrayType>(AT))
5262 PType = PVDecl->getType();
5263 } else if (PType->isFunctionType())
5264 PType = PVDecl->getType();
5265 getObjCEncodingForType(PType, S);
5266 S += charUnitsToString(ParmOffset);
5267 ParmOffset += getObjCEncodingTypeSize(PType);
5268 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005269
5270 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00005271}
5272
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005273/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5274/// method parameter or return type. If Extended, include class names and
5275/// block object types.
5276void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5277 QualType T, std::string& S,
5278 bool Extended) const {
5279 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5280 getObjCEncodingForTypeQualifier(QT, S);
5281 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005282 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005283 true /*OutermostType*/,
5284 false /*EncodingProperty*/,
5285 false /*StructField*/,
5286 Extended /*EncodeBlockParameters*/,
5287 Extended /*EncodeClassNames*/);
5288}
5289
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005290/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005291/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00005292bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005293 std::string& S,
5294 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005295 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005296 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00005297 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5298 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005299 // Compute size of all parameters.
5300 // Start with computing size of a pointer in number of bytes.
5301 // FIXME: There might(should) be a better way of doing this computation!
5302 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005303 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005304 // The first two arguments (self and _cmd) are pointers; account for
5305 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005306 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005307 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005308 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005309 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005310 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005311 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005312 continue;
5313
Ken Dyck40775002010-01-11 17:06:35 +00005314 assert (sz.isPositive() &&
5315 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005316 ParmOffset += sz;
5317 }
Ken Dyck40775002010-01-11 17:06:35 +00005318 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005319 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005320 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005321
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005322 // Argument types.
5323 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005324 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005325 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005326 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005327 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005328 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005329 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5330 // Use array's original type only if it has known number of
5331 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005332 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005333 PType = PVDecl->getType();
5334 } else if (PType->isFunctionType())
5335 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005336 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5337 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005338 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005339 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005340 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005341
5342 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005343}
5344
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005345ObjCPropertyImplDecl *
5346ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5347 const ObjCPropertyDecl *PD,
5348 const Decl *Container) const {
5349 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005350 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005351 if (const ObjCCategoryImplDecl *CID =
5352 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005353 for (auto *PID : CID->property_impls())
5354 if (PID->getPropertyDecl() == PD)
5355 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005356 } else {
5357 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5358 for (auto *PID : OID->property_impls())
5359 if (PID->getPropertyDecl() == PD)
5360 return PID;
5361 }
5362 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005363}
5364
Daniel Dunbar4932b362008-08-28 04:38:10 +00005365/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005366/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005367/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5368/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005369/// Property attributes are stored as a comma-delimited C string. The simple
5370/// attributes readonly and bycopy are encoded as single characters. The
5371/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5372/// encoded as single characters, followed by an identifier. Property types
5373/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005374/// these attributes are defined by the following enumeration:
5375/// @code
5376/// enum PropertyAttributes {
5377/// kPropertyReadOnly = 'R', // property is read-only.
5378/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5379/// kPropertyByref = '&', // property is a reference to the value last assigned
5380/// kPropertyDynamic = 'D', // property is dynamic
5381/// kPropertyGetter = 'G', // followed by getter selector name
5382/// kPropertySetter = 'S', // followed by setter selector name
5383/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005384/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005385/// kPropertyWeak = 'W' // 'weak' property
5386/// kPropertyStrong = 'P' // property GC'able
5387/// kPropertyNonAtomic = 'N' // property non-atomic
5388/// };
5389/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005390void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005391 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005392 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005393 // Collect information from the property implementation decl(s).
5394 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005395 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005396
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005397 if (ObjCPropertyImplDecl *PropertyImpDecl =
5398 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5399 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5400 Dynamic = true;
5401 else
5402 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005403 }
5404
5405 // FIXME: This is not very efficient.
5406 S = "T";
5407
5408 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005409 // GCC has some special rules regarding encoding of properties which
5410 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005411 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005412
5413 if (PD->isReadOnly()) {
5414 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005415 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5416 S += ",C";
5417 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5418 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005419 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5420 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005421 } else {
5422 switch (PD->getSetterKind()) {
5423 case ObjCPropertyDecl::Assign: break;
5424 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005425 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005426 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005427 }
5428 }
5429
5430 // It really isn't clear at all what this means, since properties
5431 // are "dynamic by default".
5432 if (Dynamic)
5433 S += ",D";
5434
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005435 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5436 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005437
Daniel Dunbar4932b362008-08-28 04:38:10 +00005438 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5439 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005440 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005441 }
5442
5443 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5444 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005445 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005446 }
5447
5448 if (SynthesizePID) {
5449 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5450 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005451 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005452 }
5453
5454 // FIXME: OBJCGC: weak & strong
5455}
5456
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005457/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005458/// Another legacy compatibility encoding: 32-bit longs are encoded as
5459/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005460/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5461///
5462void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005463 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005464 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005465 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005466 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005467 else
Jay Foad39c79802011-01-12 09:06:06 +00005468 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005469 PointeeTy = IntTy;
5470 }
5471 }
5472}
5473
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005474void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005475 const FieldDecl *Field,
5476 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005477 // We follow the behavior of gcc, expanding structures which are
5478 // directly pointed to, and expanding embedded structures. Note that
5479 // these rules are sufficient to prevent recursive encoding of the
5480 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005481 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005482 true /* outermost type */, false, false,
5483 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005484}
5485
Joe Groff98ac7d22014-07-07 22:25:15 +00005486void ASTContext::getObjCEncodingForPropertyType(QualType T,
5487 std::string& S) const {
5488 // Encode result type.
5489 // GCC has some special rules regarding encoding of properties which
5490 // closely resembles encoding of ivars.
5491 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5492 true /* outermost type */,
5493 true /* encoding property */);
5494}
5495
John McCall393a78d2012-12-20 02:45:14 +00005496static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5497 BuiltinType::Kind kind) {
5498 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005499 case BuiltinType::Void: return 'v';
5500 case BuiltinType::Bool: return 'B';
5501 case BuiltinType::Char_U:
5502 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005503 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005504 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005505 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005506 case BuiltinType::UInt: return 'I';
5507 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005508 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005509 case BuiltinType::UInt128: return 'T';
5510 case BuiltinType::ULongLong: return 'Q';
5511 case BuiltinType::Char_S:
5512 case BuiltinType::SChar: return 'c';
5513 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005514 case BuiltinType::WChar_S:
5515 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005516 case BuiltinType::Int: return 'i';
5517 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005518 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005519 case BuiltinType::LongLong: return 'q';
5520 case BuiltinType::Int128: return 't';
5521 case BuiltinType::Float: return 'f';
5522 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005523 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005524 case BuiltinType::NullPtr: return '*'; // like char*
5525
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005526 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005527 case BuiltinType::Half:
5528 // FIXME: potentially need @encodes for these!
5529 return ' ';
5530
5531 case BuiltinType::ObjCId:
5532 case BuiltinType::ObjCClass:
5533 case BuiltinType::ObjCSel:
5534 llvm_unreachable("@encoding ObjC primitive type");
5535
5536 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005537#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5538 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005539#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005540 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005541 case BuiltinType::OCLClkEvent:
5542 case BuiltinType::OCLQueue:
5543 case BuiltinType::OCLNDRange:
5544 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005545 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005546 case BuiltinType::Dependent:
5547#define BUILTIN_TYPE(KIND, ID)
5548#define PLACEHOLDER_TYPE(KIND, ID) \
5549 case BuiltinType::KIND:
5550#include "clang/AST/BuiltinTypes.def"
5551 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005552 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005553 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005554}
5555
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005556static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5557 EnumDecl *Enum = ET->getDecl();
5558
5559 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5560 if (!Enum->isFixed())
5561 return 'i';
5562
5563 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005564 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5565 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005566}
5567
Jay Foad39c79802011-01-12 09:06:06 +00005568static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005569 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005570 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005571 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005572 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5573 // The GNU runtime requires more information; bitfields are encoded as b,
5574 // then the offset (in bits) of the first element, then the type of the
5575 // bitfield, then the size in bits. For example, in this structure:
5576 //
5577 // struct
5578 // {
5579 // int integer;
5580 // int flags:2;
5581 // };
5582 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5583 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5584 // information is not especially sensible, but we're stuck with it for
5585 // compatibility with GCC, although providing it breaks anything that
5586 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005587 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005588 const RecordDecl *RD = FD->getParent();
5589 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005590 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005591 if (const EnumType *ET = T->getAs<EnumType>())
5592 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005593 else {
5594 const BuiltinType *BT = T->castAs<BuiltinType>();
5595 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5596 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005597 }
Richard Smithcaf33902011-10-10 18:28:20 +00005598 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005599}
5600
Daniel Dunbar07d07852009-10-18 21:17:35 +00005601// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005602void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5603 bool ExpandPointedToStructures,
5604 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005605 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005606 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005607 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005608 bool StructField,
5609 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005610 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005611 bool EncodePointerToObjCTypedef,
5612 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00005613 CanQualType CT = getCanonicalType(T);
5614 switch (CT->getTypeClass()) {
5615 case Type::Builtin:
5616 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005617 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005618 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005619 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5620 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5621 else
5622 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005623 return;
Mike Stump11289f42009-09-09 15:08:12 +00005624
John McCall393a78d2012-12-20 02:45:14 +00005625 case Type::Complex: {
5626 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005627 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005628 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005629 return;
5630 }
John McCall393a78d2012-12-20 02:45:14 +00005631
5632 case Type::Atomic: {
5633 const AtomicType *AT = T->castAs<AtomicType>();
5634 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005635 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00005636 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005637 }
John McCall393a78d2012-12-20 02:45:14 +00005638
5639 // encoding for pointer or reference types.
5640 case Type::Pointer:
5641 case Type::LValueReference:
5642 case Type::RValueReference: {
5643 QualType PointeeTy;
5644 if (isa<PointerType>(CT)) {
5645 const PointerType *PT = T->castAs<PointerType>();
5646 if (PT->isObjCSelType()) {
5647 S += ':';
5648 return;
5649 }
5650 PointeeTy = PT->getPointeeType();
5651 } else {
5652 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5653 }
5654
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005655 bool isReadOnly = false;
5656 // For historical/compatibility reasons, the read-only qualifier of the
5657 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5658 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005659 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005660 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005661 if (OutermostType && T.isConstQualified()) {
5662 isReadOnly = true;
5663 S += 'r';
5664 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005665 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005666 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005667 while (P->getAs<PointerType>())
5668 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005669 if (P.isConstQualified()) {
5670 isReadOnly = true;
5671 S += 'r';
5672 }
5673 }
5674 if (isReadOnly) {
5675 // Another legacy compatibility encoding. Some ObjC qualifier and type
5676 // combinations need to be rearranged.
5677 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005678 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005679 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005680 }
Mike Stump11289f42009-09-09 15:08:12 +00005681
Anders Carlssond8499822007-10-29 05:01:08 +00005682 if (PointeeTy->isCharType()) {
5683 // char pointer types should be encoded as '*' unless it is a
5684 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005685 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005686 S += '*';
5687 return;
5688 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005689 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005690 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5691 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5692 S += '#';
5693 return;
5694 }
5695 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5696 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5697 S += '@';
5698 return;
5699 }
5700 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005701 }
Anders Carlssond8499822007-10-29 05:01:08 +00005702 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005703 getLegacyIntegralTypeEncoding(PointeeTy);
5704
Mike Stump11289f42009-09-09 15:08:12 +00005705 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005706 nullptr, false, false, false, false, false, false,
5707 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005708 return;
5709 }
John McCall393a78d2012-12-20 02:45:14 +00005710
5711 case Type::ConstantArray:
5712 case Type::IncompleteArray:
5713 case Type::VariableArray: {
5714 const ArrayType *AT = cast<ArrayType>(CT);
5715
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005716 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005717 // Incomplete arrays are encoded as a pointer to the array element.
5718 S += '^';
5719
Mike Stump11289f42009-09-09 15:08:12 +00005720 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005721 false, ExpandStructures, FD);
5722 } else {
5723 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005724
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005725 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5726 S += llvm::utostr(CAT->getSize().getZExtValue());
5727 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005728 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005729 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5730 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005731 S += '0';
5732 }
Mike Stump11289f42009-09-09 15:08:12 +00005733
5734 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005735 false, ExpandStructures, FD,
5736 false, false, false, false, false, false,
5737 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00005738 S += ']';
5739 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005740 return;
5741 }
Mike Stump11289f42009-09-09 15:08:12 +00005742
John McCall393a78d2012-12-20 02:45:14 +00005743 case Type::FunctionNoProto:
5744 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005745 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005746 return;
Mike Stump11289f42009-09-09 15:08:12 +00005747
John McCall393a78d2012-12-20 02:45:14 +00005748 case Type::Record: {
5749 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005750 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005751 // Anonymous structures print as '?'
5752 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5753 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005754 if (ClassTemplateSpecializationDecl *Spec
5755 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5756 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005757 llvm::raw_string_ostream OS(S);
5758 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005759 TemplateArgs.data(),
5760 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005761 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005762 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005763 } else {
5764 S += '?';
5765 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005766 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005767 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005768 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005769 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005770 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005771 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005772 if (FD) {
5773 S += '"';
5774 S += Field->getNameAsString();
5775 S += '"';
5776 }
Mike Stump11289f42009-09-09 15:08:12 +00005777
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005778 // Special case bit-fields.
5779 if (Field->isBitField()) {
5780 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005781 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005782 } else {
5783 QualType qt = Field->getType();
5784 getLegacyIntegralTypeEncoding(qt);
5785 getObjCEncodingForTypeImpl(qt, S, false, true,
5786 FD, /*OutermostType*/false,
5787 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005788 /*StructField*/true,
5789 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005790 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005791 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005792 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005793 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005794 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005795 return;
5796 }
Mike Stump11289f42009-09-09 15:08:12 +00005797
John McCall393a78d2012-12-20 02:45:14 +00005798 case Type::BlockPointer: {
5799 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005800 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005801 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005802 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005803
5804 S += '<';
5805 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005806 getObjCEncodingForTypeImpl(
5807 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5808 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005809 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5810 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005811 // Block self
5812 S += "@?";
5813 // Block parameters
5814 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00005815 for (const auto &I : FPT->param_types())
5816 getObjCEncodingForTypeImpl(
5817 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5818 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005819 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5820 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005821 }
5822 S += '>';
5823 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005824 return;
5825 }
Mike Stump11289f42009-09-09 15:08:12 +00005826
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005827 case Type::ObjCObject: {
5828 // hack to match legacy encoding of *id and *Class
5829 QualType Ty = getObjCObjectPointerType(CT);
5830 if (Ty->isObjCIdType()) {
5831 S += "{objc_object=}";
5832 return;
5833 }
5834 else if (Ty->isObjCClassType()) {
5835 S += "{objc_class=}";
5836 return;
5837 }
5838 }
5839
John McCall393a78d2012-12-20 02:45:14 +00005840 case Type::ObjCInterface: {
5841 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005842 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00005843 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005844 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005845 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005846 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005847 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005848 DeepCollectObjCIvars(OI, true, Ivars);
5849 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005850 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005851 if (Field->isBitField())
5852 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005853 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005854 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5855 false, false, false, false, false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005856 EncodePointerToObjCTypedef,
5857 NotEncodedT);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005858 }
5859 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005860 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005861 }
Mike Stump11289f42009-09-09 15:08:12 +00005862
John McCall393a78d2012-12-20 02:45:14 +00005863 case Type::ObjCObjectPointer: {
5864 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005865 if (OPT->isObjCIdType()) {
5866 S += '@';
5867 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005868 }
Mike Stump11289f42009-09-09 15:08:12 +00005869
Steve Narofff0c86112009-10-28 22:03:49 +00005870 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5871 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5872 // Since this is a binary compatibility issue, need to consult with runtime
5873 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005874 S += '#';
5875 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005876 }
Mike Stump11289f42009-09-09 15:08:12 +00005877
Chris Lattnere7cabb92009-07-13 00:10:46 +00005878 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005879 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005880 ExpandPointedToStructures,
5881 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005882 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005883 // Note that we do extended encoding of protocol qualifer list
5884 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005885 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00005886 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005887 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005888 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005889 S += '>';
5890 }
5891 S += '"';
5892 }
5893 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005894 }
Mike Stump11289f42009-09-09 15:08:12 +00005895
Chris Lattnere7cabb92009-07-13 00:10:46 +00005896 QualType PointeeTy = OPT->getPointeeType();
5897 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005898 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5899 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005900 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005901 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005902 // {...};
5903 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005904 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005905 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005906 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5907 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5908 DeepCollectObjCIvars(OI, true, Ivars);
5909 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5910 if (cast<FieldDecl>(Ivars[i]) == FD) {
5911 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005912 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005913 S += '}';
5914 return;
5915 }
5916 }
5917 }
Mike Stump11289f42009-09-09 15:08:12 +00005918 getObjCEncodingForTypeImpl(PointeeTy, S,
5919 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00005920 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005921 false, false, false, false, false,
5922 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005923 return;
5924 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005925
5926 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005927 if (OPT->getInterfaceDecl() &&
5928 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005929 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005930 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00005931 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005932 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00005933 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00005934 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005935 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005936 S += '"';
5937 }
5938 return;
5939 }
Mike Stump11289f42009-09-09 15:08:12 +00005940
John McCalla9e6e8d2010-05-17 23:56:34 +00005941 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005942 // FIXME: we shoul do better than that. 'M' is available.
5943 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005944 // This matches gcc's encoding, even though technically it is insufficient.
5945 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00005946 case Type::Vector:
5947 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005948 // Until we have a coherent encoding of these three types, issue warning.
5949 { if (NotEncodedT)
5950 *NotEncodedT = T;
5951 return;
5952 }
5953
5954 // We could see an undeduced auto type here during error recovery.
5955 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00005956 case Type::Auto:
Richard Smith27d807c2013-04-30 13:56:41 +00005957 return;
5958
Xiuli Pan9c14e282016-01-09 12:53:17 +00005959 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00005960#define ABSTRACT_TYPE(KIND, BASE)
5961#define TYPE(KIND, BASE)
5962#define DEPENDENT_TYPE(KIND, BASE) \
5963 case Type::KIND:
5964#define NON_CANONICAL_TYPE(KIND, BASE) \
5965 case Type::KIND:
5966#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5967 case Type::KIND:
5968#include "clang/AST/TypeNodes.def"
5969 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005970 }
John McCall393a78d2012-12-20 02:45:14 +00005971 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005972}
5973
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005974void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5975 std::string &S,
5976 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005977 bool includeVBases,
5978 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005979 assert(RDecl && "Expected non-null RecordDecl");
5980 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00005981 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005982 return;
5983
5984 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5985 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5986 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5987
5988 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00005989 for (const auto &BI : CXXRec->bases()) {
5990 if (!BI.isVirtual()) {
5991 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005992 if (base->isEmpty())
5993 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005994 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005995 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5996 std::make_pair(offs, base));
5997 }
5998 }
5999 }
6000
6001 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006002 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006003 uint64_t offs = layout.getFieldOffset(i);
6004 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006005 std::make_pair(offs, Field));
6006 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006007 }
6008
6009 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006010 for (const auto &BI : CXXRec->vbases()) {
6011 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006012 if (base->isEmpty())
6013 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006014 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006015 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6016 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006017 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6018 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006019 }
6020 }
6021
6022 CharUnits size;
6023 if (CXXRec) {
6024 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6025 } else {
6026 size = layout.getSize();
6027 }
6028
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006029#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006030 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006031#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006032 std::multimap<uint64_t, NamedDecl *>::iterator
6033 CurLayObj = FieldOrBaseOffsets.begin();
6034
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006035 if (CXXRec && CXXRec->isDynamicClass() &&
6036 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006037 if (FD) {
6038 S += "\"_vptr$";
6039 std::string recname = CXXRec->getNameAsString();
6040 if (recname.empty()) recname = "?";
6041 S += recname;
6042 S += '"';
6043 }
6044 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006045#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006046 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006047#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006048 }
6049
6050 if (!RDecl->hasFlexibleArrayMember()) {
6051 // Mark the end of the structure.
6052 uint64_t offs = toBits(size);
6053 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006054 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006055 }
6056
6057 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006058#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006059 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006060 if (CurOffs < CurLayObj->first) {
6061 uint64_t padding = CurLayObj->first - CurOffs;
6062 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6063 // packing/alignment of members is different that normal, in which case
6064 // the encoding will be out-of-sync with the real layout.
6065 // If the runtime switches to just consider the size of types without
6066 // taking into account alignment, we could make padding explicit in the
6067 // encoding (e.g. using arrays of chars). The encoding strings would be
6068 // longer then though.
6069 CurOffs += padding;
6070 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006071#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006072
6073 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006074 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006075 break; // reached end of structure.
6076
6077 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6078 // We expand the bases without their virtual bases since those are going
6079 // in the initial structure. Note that this differs from gcc which
6080 // expands virtual bases each time one is encountered in the hierarchy,
6081 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006082 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6083 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006084 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006085#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006086 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006087#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006088 } else {
6089 FieldDecl *field = cast<FieldDecl>(dcl);
6090 if (FD) {
6091 S += '"';
6092 S += field->getNameAsString();
6093 S += '"';
6094 }
6095
6096 if (field->isBitField()) {
6097 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006098#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006099 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006100#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006101 } else {
6102 QualType qt = field->getType();
6103 getLegacyIntegralTypeEncoding(qt);
6104 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6105 /*OutermostType*/false,
6106 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006107 /*StructField*/true,
6108 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006109#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006110 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006111#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006112 }
6113 }
6114 }
6115}
6116
Mike Stump11289f42009-09-09 15:08:12 +00006117void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006118 std::string& S) const {
6119 if (QT & Decl::OBJC_TQ_In)
6120 S += 'n';
6121 if (QT & Decl::OBJC_TQ_Inout)
6122 S += 'N';
6123 if (QT & Decl::OBJC_TQ_Out)
6124 S += 'o';
6125 if (QT & Decl::OBJC_TQ_Bycopy)
6126 S += 'O';
6127 if (QT & Decl::OBJC_TQ_Byref)
6128 S += 'R';
6129 if (QT & Decl::OBJC_TQ_Oneway)
6130 S += 'V';
6131}
6132
Douglas Gregor3ea72692011-08-12 05:46:01 +00006133TypedefDecl *ASTContext::getObjCIdDecl() const {
6134 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006135 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006136 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006137 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006138 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006139 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006140}
6141
Douglas Gregor52e02802011-08-12 06:17:30 +00006142TypedefDecl *ASTContext::getObjCSelDecl() const {
6143 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006144 QualType T = getPointerType(ObjCBuiltinSelTy);
6145 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006146 }
6147 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006148}
6149
Douglas Gregor0a586182011-08-12 05:59:41 +00006150TypedefDecl *ASTContext::getObjCClassDecl() const {
6151 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006152 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006153 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006154 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006155 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006156 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006157}
6158
Douglas Gregord53ae832012-01-17 18:09:05 +00006159ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6160 if (!ObjCProtocolClassDecl) {
6161 ObjCProtocolClassDecl
6162 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6163 SourceLocation(),
6164 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006165 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006166 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006167 SourceLocation(), true);
6168 }
6169
6170 return ObjCProtocolClassDecl;
6171}
6172
Meador Inge5d3fb222012-06-16 03:34:49 +00006173//===----------------------------------------------------------------------===//
6174// __builtin_va_list Construction Functions
6175//===----------------------------------------------------------------------===//
6176
Charles Davisc7d5c942015-09-17 20:55:33 +00006177static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6178 StringRef Name) {
6179 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006180 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006181 return Context->buildImplicitTypedef(T, Name);
6182}
6183
6184static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6185 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6186}
6187
6188static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6189 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006190}
6191
6192static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6193 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006194 QualType T = Context->getPointerType(Context->VoidTy);
6195 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006196}
6197
Tim Northover9bb857a2013-01-31 12:13:10 +00006198static TypedefDecl *
6199CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006200 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006201 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006202 if (Context->getLangOpts().CPlusPlus) {
6203 // namespace std { struct __va_list {
6204 NamespaceDecl *NS;
6205 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6206 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006207 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006208 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006209 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006210 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006211 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006212 }
6213
6214 VaListTagDecl->startDefinition();
6215
6216 const size_t NumFields = 5;
6217 QualType FieldTypes[NumFields];
6218 const char *FieldNames[NumFields];
6219
6220 // void *__stack;
6221 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6222 FieldNames[0] = "__stack";
6223
6224 // void *__gr_top;
6225 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6226 FieldNames[1] = "__gr_top";
6227
6228 // void *__vr_top;
6229 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6230 FieldNames[2] = "__vr_top";
6231
6232 // int __gr_offs;
6233 FieldTypes[3] = Context->IntTy;
6234 FieldNames[3] = "__gr_offs";
6235
6236 // int __vr_offs;
6237 FieldTypes[4] = Context->IntTy;
6238 FieldNames[4] = "__vr_offs";
6239
6240 // Create fields
6241 for (unsigned i = 0; i < NumFields; ++i) {
6242 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6243 VaListTagDecl,
6244 SourceLocation(),
6245 SourceLocation(),
6246 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006247 FieldTypes[i], /*TInfo=*/nullptr,
6248 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006249 /*Mutable=*/false,
6250 ICIS_NoInit);
6251 Field->setAccess(AS_public);
6252 VaListTagDecl->addDecl(Field);
6253 }
6254 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006255 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006256 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006257
6258 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006259 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006260}
6261
Meador Inge5d3fb222012-06-16 03:34:49 +00006262static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6263 // typedef struct __va_list_tag {
6264 RecordDecl *VaListTagDecl;
6265
Alp Toker2dea15b2013-12-17 01:22:38 +00006266 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006267 VaListTagDecl->startDefinition();
6268
6269 const size_t NumFields = 5;
6270 QualType FieldTypes[NumFields];
6271 const char *FieldNames[NumFields];
6272
6273 // unsigned char gpr;
6274 FieldTypes[0] = Context->UnsignedCharTy;
6275 FieldNames[0] = "gpr";
6276
6277 // unsigned char fpr;
6278 FieldTypes[1] = Context->UnsignedCharTy;
6279 FieldNames[1] = "fpr";
6280
6281 // unsigned short reserved;
6282 FieldTypes[2] = Context->UnsignedShortTy;
6283 FieldNames[2] = "reserved";
6284
6285 // void* overflow_arg_area;
6286 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6287 FieldNames[3] = "overflow_arg_area";
6288
6289 // void* reg_save_area;
6290 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6291 FieldNames[4] = "reg_save_area";
6292
6293 // Create fields
6294 for (unsigned i = 0; i < NumFields; ++i) {
6295 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6296 SourceLocation(),
6297 SourceLocation(),
6298 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006299 FieldTypes[i], /*TInfo=*/nullptr,
6300 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006301 /*Mutable=*/false,
6302 ICIS_NoInit);
6303 Field->setAccess(AS_public);
6304 VaListTagDecl->addDecl(Field);
6305 }
6306 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006307 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006308 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6309
6310 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006311 TypedefDecl *VaListTagTypedefDecl =
6312 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6313
Meador Inge5d3fb222012-06-16 03:34:49 +00006314 QualType VaListTagTypedefType =
6315 Context->getTypedefType(VaListTagTypedefDecl);
6316
6317 // typedef __va_list_tag __builtin_va_list[1];
6318 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6319 QualType VaListTagArrayType
6320 = Context->getConstantArrayType(VaListTagTypedefType,
6321 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006322 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006323}
6324
6325static TypedefDecl *
6326CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006327 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006328 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006329 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006330 VaListTagDecl->startDefinition();
6331
6332 const size_t NumFields = 4;
6333 QualType FieldTypes[NumFields];
6334 const char *FieldNames[NumFields];
6335
6336 // unsigned gp_offset;
6337 FieldTypes[0] = Context->UnsignedIntTy;
6338 FieldNames[0] = "gp_offset";
6339
6340 // unsigned fp_offset;
6341 FieldTypes[1] = Context->UnsignedIntTy;
6342 FieldNames[1] = "fp_offset";
6343
6344 // void* overflow_arg_area;
6345 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6346 FieldNames[2] = "overflow_arg_area";
6347
6348 // void* reg_save_area;
6349 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6350 FieldNames[3] = "reg_save_area";
6351
6352 // Create fields
6353 for (unsigned i = 0; i < NumFields; ++i) {
6354 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6355 VaListTagDecl,
6356 SourceLocation(),
6357 SourceLocation(),
6358 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006359 FieldTypes[i], /*TInfo=*/nullptr,
6360 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006361 /*Mutable=*/false,
6362 ICIS_NoInit);
6363 Field->setAccess(AS_public);
6364 VaListTagDecl->addDecl(Field);
6365 }
6366 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006367 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006368 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6369
Richard Smith9b88a4c2015-07-27 05:40:23 +00006370 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006371
Richard Smith9b88a4c2015-07-27 05:40:23 +00006372 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006373 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006374 QualType VaListTagArrayType =
6375 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006376 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006377}
6378
6379static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6380 // typedef int __builtin_va_list[4];
6381 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6382 QualType IntArrayType
6383 = Context->getConstantArrayType(Context->IntTy,
6384 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006385 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006386}
6387
Logan Chien57086ce2012-10-10 06:56:20 +00006388static TypedefDecl *
6389CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006390 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006391 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006392 if (Context->getLangOpts().CPlusPlus) {
6393 // namespace std { struct __va_list {
6394 NamespaceDecl *NS;
6395 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6396 Context->getTranslationUnitDecl(),
6397 /*Inline*/false, SourceLocation(),
6398 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006399 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006400 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006401 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006402 }
6403
6404 VaListDecl->startDefinition();
6405
6406 // void * __ap;
6407 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6408 VaListDecl,
6409 SourceLocation(),
6410 SourceLocation(),
6411 &Context->Idents.get("__ap"),
6412 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006413 /*TInfo=*/nullptr,
6414 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006415 /*Mutable=*/false,
6416 ICIS_NoInit);
6417 Field->setAccess(AS_public);
6418 VaListDecl->addDecl(Field);
6419
6420 // };
6421 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006422 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006423
6424 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006425 QualType T = Context->getRecordType(VaListDecl);
6426 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006427}
6428
Ulrich Weigand47445072013-05-06 16:26:41 +00006429static TypedefDecl *
6430CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006431 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006432 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006433 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006434 VaListTagDecl->startDefinition();
6435
6436 const size_t NumFields = 4;
6437 QualType FieldTypes[NumFields];
6438 const char *FieldNames[NumFields];
6439
6440 // long __gpr;
6441 FieldTypes[0] = Context->LongTy;
6442 FieldNames[0] = "__gpr";
6443
6444 // long __fpr;
6445 FieldTypes[1] = Context->LongTy;
6446 FieldNames[1] = "__fpr";
6447
6448 // void *__overflow_arg_area;
6449 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6450 FieldNames[2] = "__overflow_arg_area";
6451
6452 // void *__reg_save_area;
6453 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6454 FieldNames[3] = "__reg_save_area";
6455
6456 // Create fields
6457 for (unsigned i = 0; i < NumFields; ++i) {
6458 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6459 VaListTagDecl,
6460 SourceLocation(),
6461 SourceLocation(),
6462 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006463 FieldTypes[i], /*TInfo=*/nullptr,
6464 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006465 /*Mutable=*/false,
6466 ICIS_NoInit);
6467 Field->setAccess(AS_public);
6468 VaListTagDecl->addDecl(Field);
6469 }
6470 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006471 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006472 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006473
Richard Smith9b88a4c2015-07-27 05:40:23 +00006474 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006475
6476 // typedef __va_list_tag __builtin_va_list[1];
6477 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006478 QualType VaListTagArrayType =
6479 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006480
Alp Toker56b5cc92013-12-15 10:36:26 +00006481 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006482}
6483
Meador Inge5d3fb222012-06-16 03:34:49 +00006484static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6485 TargetInfo::BuiltinVaListKind Kind) {
6486 switch (Kind) {
6487 case TargetInfo::CharPtrBuiltinVaList:
6488 return CreateCharPtrBuiltinVaListDecl(Context);
6489 case TargetInfo::VoidPtrBuiltinVaList:
6490 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006491 case TargetInfo::AArch64ABIBuiltinVaList:
6492 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006493 case TargetInfo::PowerABIBuiltinVaList:
6494 return CreatePowerABIBuiltinVaListDecl(Context);
6495 case TargetInfo::X86_64ABIBuiltinVaList:
6496 return CreateX86_64ABIBuiltinVaListDecl(Context);
6497 case TargetInfo::PNaClABIBuiltinVaList:
6498 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006499 case TargetInfo::AAPCSABIBuiltinVaList:
6500 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006501 case TargetInfo::SystemZBuiltinVaList:
6502 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006503 }
6504
6505 llvm_unreachable("Unhandled __builtin_va_list type kind");
6506}
6507
6508TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006509 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006510 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006511 assert(BuiltinVaListDecl->isImplicit());
6512 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006513
6514 return BuiltinVaListDecl;
6515}
6516
Richard Smith9b88a4c2015-07-27 05:40:23 +00006517Decl *ASTContext::getVaListTagDecl() const {
6518 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006519 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006520 if (!VaListTagDecl)
6521 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006522
Richard Smith9b88a4c2015-07-27 05:40:23 +00006523 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006524}
6525
Charles Davisc7d5c942015-09-17 20:55:33 +00006526TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6527 if (!BuiltinMSVaListDecl)
6528 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6529
6530 return BuiltinMSVaListDecl;
6531}
6532
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006533void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006534 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006535 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006536
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006537 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006538}
6539
John McCalld28ae272009-12-02 08:04:21 +00006540/// \brief Retrieve the template name that corresponds to a non-empty
6541/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006542TemplateName
6543ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6544 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006545 unsigned size = End - Begin;
6546 assert(size > 1 && "set is not overloaded!");
6547
6548 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6549 size * sizeof(FunctionTemplateDecl*));
6550 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6551
6552 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006553 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006554 NamedDecl *D = *I;
6555 assert(isa<FunctionTemplateDecl>(D) ||
6556 (isa<UsingShadowDecl>(D) &&
6557 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6558 *Storage++ = D;
6559 }
6560
6561 return TemplateName(OT);
6562}
6563
Douglas Gregordc572a32009-03-30 22:58:21 +00006564/// \brief Retrieve the template name that represents a qualified
6565/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006566TemplateName
6567ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6568 bool TemplateKeyword,
6569 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006570 assert(NNS && "Missing nested-name-specifier in qualified template name");
6571
Douglas Gregorc42075a2010-02-04 18:10:26 +00006572 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006573 llvm::FoldingSetNodeID ID;
6574 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6575
Craig Topper36250ad2014-05-12 05:36:57 +00006576 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006577 QualifiedTemplateName *QTN =
6578 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6579 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006580 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6581 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006582 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6583 }
6584
6585 return TemplateName(QTN);
6586}
6587
6588/// \brief Retrieve the template name that represents a dependent
6589/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006590TemplateName
6591ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6592 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006593 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006594 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006595
6596 llvm::FoldingSetNodeID ID;
6597 DependentTemplateName::Profile(ID, NNS, Name);
6598
Craig Topper36250ad2014-05-12 05:36:57 +00006599 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006600 DependentTemplateName *QTN =
6601 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6602
6603 if (QTN)
6604 return TemplateName(QTN);
6605
6606 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6607 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006608 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6609 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006610 } else {
6611 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006612 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6613 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006614 DependentTemplateName *CheckQTN =
6615 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6616 assert(!CheckQTN && "Dependent type name canonicalization broken");
6617 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006618 }
6619
6620 DependentTemplateNames.InsertNode(QTN, InsertPos);
6621 return TemplateName(QTN);
6622}
6623
Douglas Gregor71395fa2009-11-04 00:56:37 +00006624/// \brief Retrieve the template name that represents a dependent
6625/// template name such as \c MetaFun::template operator+.
6626TemplateName
6627ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006628 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006629 assert((!NNS || NNS->isDependent()) &&
6630 "Nested name specifier must be dependent");
6631
6632 llvm::FoldingSetNodeID ID;
6633 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00006634
6635 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006636 DependentTemplateName *QTN
6637 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006638
6639 if (QTN)
6640 return TemplateName(QTN);
6641
6642 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6643 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006644 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6645 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006646 } else {
6647 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006648 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6649 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006650
6651 DependentTemplateName *CheckQTN
6652 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6653 assert(!CheckQTN && "Dependent template name canonicalization broken");
6654 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006655 }
6656
6657 DependentTemplateNames.InsertNode(QTN, InsertPos);
6658 return TemplateName(QTN);
6659}
6660
Douglas Gregor5590be02011-01-15 06:45:20 +00006661TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006662ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6663 TemplateName replacement) const {
6664 llvm::FoldingSetNodeID ID;
6665 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00006666
6667 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00006668 SubstTemplateTemplateParmStorage *subst
6669 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6670
6671 if (!subst) {
6672 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6673 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6674 }
6675
6676 return TemplateName(subst);
6677}
6678
6679TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006680ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6681 const TemplateArgument &ArgPack) const {
6682 ASTContext &Self = const_cast<ASTContext &>(*this);
6683 llvm::FoldingSetNodeID ID;
6684 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00006685
6686 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00006687 SubstTemplateTemplateParmPackStorage *Subst
6688 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6689
6690 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006691 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006692 ArgPack.pack_size(),
6693 ArgPack.pack_begin());
6694 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6695 }
6696
6697 return TemplateName(Subst);
6698}
6699
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006700/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006701/// TargetInfo, produce the corresponding type. The unsigned @p Type
6702/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006703CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006704 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006705 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006706 case TargetInfo::SignedChar: return SignedCharTy;
6707 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006708 case TargetInfo::SignedShort: return ShortTy;
6709 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6710 case TargetInfo::SignedInt: return IntTy;
6711 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6712 case TargetInfo::SignedLong: return LongTy;
6713 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6714 case TargetInfo::SignedLongLong: return LongLongTy;
6715 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6716 }
6717
David Blaikie83d382b2011-09-23 05:06:16 +00006718 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006719}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006720
6721//===----------------------------------------------------------------------===//
6722// Type Predicates.
6723//===----------------------------------------------------------------------===//
6724
Fariborz Jahanian96207692009-02-18 21:49:28 +00006725/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6726/// garbage collection attribute.
6727///
John McCall553d45a2011-01-12 00:34:59 +00006728Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006729 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006730 return Qualifiers::GCNone;
6731
David Blaikiebbafb8a2012-03-11 07:00:24 +00006732 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006733 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6734
6735 // Default behaviour under objective-C's gc is for ObjC pointers
6736 // (or pointers to them) be treated as though they were declared
6737 // as __strong.
6738 if (GCAttrs == Qualifiers::GCNone) {
6739 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6740 return Qualifiers::Strong;
6741 else if (Ty->isPointerType())
6742 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6743 } else {
6744 // It's not valid to set GC attributes on anything that isn't a
6745 // pointer.
6746#ifndef NDEBUG
6747 QualType CT = Ty->getCanonicalTypeInternal();
6748 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6749 CT = AT->getElementType();
6750 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6751#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006752 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006753 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006754}
6755
Chris Lattner49af6a42008-04-07 06:51:04 +00006756//===----------------------------------------------------------------------===//
6757// Type Compatibility Testing
6758//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006759
Mike Stump11289f42009-09-09 15:08:12 +00006760/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006761/// compatible.
6762static bool areCompatVectorTypes(const VectorType *LHS,
6763 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006764 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006765 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006766 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006767}
6768
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006769bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6770 QualType SecondVec) {
6771 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6772 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6773
6774 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6775 return true;
6776
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006777 // Treat Neon vector types and most AltiVec vector types as if they are the
6778 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006779 const VectorType *First = FirstVec->getAs<VectorType>();
6780 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006781 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006782 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006783 First->getVectorKind() != VectorType::AltiVecPixel &&
6784 First->getVectorKind() != VectorType::AltiVecBool &&
6785 Second->getVectorKind() != VectorType::AltiVecPixel &&
6786 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006787 return true;
6788
6789 return false;
6790}
6791
Steve Naroff8e6aee52009-07-23 01:01:38 +00006792//===----------------------------------------------------------------------===//
6793// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6794//===----------------------------------------------------------------------===//
6795
6796/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6797/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006798bool
6799ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6800 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006801 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006802 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006803 for (auto *PI : rProto->protocols())
6804 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006805 return true;
6806 return false;
6807}
6808
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006809/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6810/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006811bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6812 QualType rhs) {
6813 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6814 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6815 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6816
Aaron Ballman83731462014-03-17 16:14:00 +00006817 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006818 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006819 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006820 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6821 match = true;
6822 break;
6823 }
6824 }
6825 if (!match)
6826 return false;
6827 }
6828 return true;
6829}
6830
Steve Naroff8e6aee52009-07-23 01:01:38 +00006831/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6832/// ObjCQualifiedIDType.
6833bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6834 bool compare) {
6835 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006836 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006837 lhs->isObjCIdType() || lhs->isObjCClassType())
6838 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006839 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006840 rhs->isObjCIdType() || rhs->isObjCClassType())
6841 return true;
6842
6843 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006844 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006845
Steve Naroff8e6aee52009-07-23 01:01:38 +00006846 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006847
Steve Naroff8e6aee52009-07-23 01:01:38 +00006848 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006849 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006850 // make sure we check the class hierarchy.
6851 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006852 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006853 // when comparing an id<P> on lhs with a static type on rhs,
6854 // see if static class implements all of id's protocols, directly or
6855 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006856 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006857 return false;
6858 }
6859 }
6860 // If there are no qualifiers and no interface, we have an 'id'.
6861 return true;
6862 }
Mike Stump11289f42009-09-09 15:08:12 +00006863 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006864 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006865 bool match = false;
6866
6867 // when comparing an id<P> on lhs with a static type on rhs,
6868 // see if static class implements all of id's protocols, directly or
6869 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006870 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006871 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6872 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6873 match = true;
6874 break;
6875 }
6876 }
Mike Stump11289f42009-09-09 15:08:12 +00006877 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006878 // make sure we check the class hierarchy.
6879 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00006880 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006881 // when comparing an id<P> on lhs with a static type on rhs,
6882 // see if static class implements all of id's protocols, directly or
6883 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00006884 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006885 match = true;
6886 break;
6887 }
6888 }
6889 }
6890 if (!match)
6891 return false;
6892 }
Mike Stump11289f42009-09-09 15:08:12 +00006893
Steve Naroff8e6aee52009-07-23 01:01:38 +00006894 return true;
6895 }
Mike Stump11289f42009-09-09 15:08:12 +00006896
Steve Naroff8e6aee52009-07-23 01:01:38 +00006897 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6898 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6899
Mike Stump11289f42009-09-09 15:08:12 +00006900 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006901 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006902 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00006903 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006904 bool match = false;
6905
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006906 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006907 // see if static class implements all of id's protocols, directly or
6908 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006909 // First, lhs protocols in the qualifier list must be found, direct
6910 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00006911 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006912 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6913 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6914 match = true;
6915 break;
6916 }
6917 }
6918 if (!match)
6919 return false;
6920 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006921
6922 // Static class's protocols, or its super class or category protocols
6923 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6924 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6925 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6926 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6927 // This is rather dubious but matches gcc's behavior. If lhs has
6928 // no type qualifier and its class has no static protocol(s)
6929 // assume that it is mismatch.
6930 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6931 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00006932 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006933 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00006934 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006935 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6936 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6937 match = true;
6938 break;
6939 }
6940 }
6941 if (!match)
6942 return false;
6943 }
6944 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006945 return true;
6946 }
6947 return false;
6948}
6949
Eli Friedman47f77112008-08-22 00:56:42 +00006950/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006951/// compatible for assignment from RHS to LHS. This handles validation of any
6952/// protocol qualifiers on the LHS or RHS.
6953///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006954bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6955 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006956 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6957 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6958
Steve Naroff1329fa02009-07-15 18:40:39 +00006959 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006960 if (LHS->isObjCUnqualifiedIdOrClass() ||
6961 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006962 return true;
6963
Douglas Gregorab209d82015-07-07 03:58:42 +00006964 // Function object that propagates a successful result or handles
6965 // __kindof types.
6966 auto finish = [&](bool succeeded) -> bool {
6967 if (succeeded)
6968 return true;
6969
6970 if (!RHS->isKindOfType())
6971 return false;
6972
6973 // Strip off __kindof and protocol qualifiers, then check whether
6974 // we can assign the other way.
6975 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6976 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6977 };
6978
6979 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6980 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6981 QualType(RHSOPT,0),
6982 false));
6983 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006984
Douglas Gregorab209d82015-07-07 03:58:42 +00006985 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6986 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6987 QualType(RHSOPT,0)));
6988 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006989
John McCall8b07ec22010-05-15 11:32:37 +00006990 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00006991 if (LHS->getInterface() && RHS->getInterface()) {
6992 return finish(canAssignObjCInterfaces(LHS, RHS));
6993 }
Mike Stump11289f42009-09-09 15:08:12 +00006994
Steve Naroff8e6aee52009-07-23 01:01:38 +00006995 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006996}
6997
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006998/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006999/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007000/// arguments in block literals. When passed as arguments, passing 'A*' where
7001/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7002/// not OK. For the return type, the opposite is not OK.
7003bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7004 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007005 const ObjCObjectPointerType *RHSOPT,
7006 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007007
7008 // Function object that propagates a successful result or handles
7009 // __kindof types.
7010 auto finish = [&](bool succeeded) -> bool {
7011 if (succeeded)
7012 return true;
7013
7014 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7015 if (!Expected->isKindOfType())
7016 return false;
7017
7018 // Strip off __kindof and protocol qualifiers, then check whether
7019 // we can assign the other way.
7020 return canAssignObjCInterfacesInBlockPointer(
7021 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7022 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7023 BlockReturnType);
7024 };
7025
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007026 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007027 return true;
7028
7029 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007030 return finish(RHSOPT->isObjCBuiltinType() ||
7031 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007032 }
7033
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007034 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007035 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7036 QualType(RHSOPT,0),
7037 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007038
7039 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7040 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7041 if (LHS && RHS) { // We have 2 user-defined types.
7042 if (LHS != RHS) {
7043 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007044 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007045 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007046 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007047 }
7048 else
7049 return true;
7050 }
7051 return false;
7052}
7053
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007054/// Comparison routine for Objective-C protocols to be used with
7055/// llvm::array_pod_sort.
7056static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7057 ObjCProtocolDecl * const *rhs) {
7058 return (*lhs)->getName().compare((*rhs)->getName());
7059
7060}
7061
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007062/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007063/// of protocols inherited from two distinct objective-c pointer objects with
7064/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007065/// It is used to build composite qualifier list of the composite type of
7066/// the conditional expression involving two objective-c pointer objects.
7067static
7068void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007069 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007070 const ObjCObjectPointerType *LHSOPT,
7071 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007072 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007073
John McCall8b07ec22010-05-15 11:32:37 +00007074 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7075 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7076 assert(LHS->getInterface() && "LHS must have an interface base");
7077 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007078
7079 // Add all of the protocols for the LHS.
7080 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7081
7082 // Start with the protocol qualifiers.
7083 for (auto proto : LHS->quals()) {
7084 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007085 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007086
7087 // Also add the protocols associated with the LHS interface.
7088 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7089
7090 // Add all of the protocls for the RHS.
7091 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7092
7093 // Start with the protocol qualifiers.
7094 for (auto proto : RHS->quals()) {
7095 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007096 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007097
7098 // Also add the protocols associated with the RHS interface.
7099 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7100
7101 // Compute the intersection of the collected protocol sets.
7102 for (auto proto : LHSProtocolSet) {
7103 if (RHSProtocolSet.count(proto))
7104 IntersectionSet.push_back(proto);
7105 }
7106
7107 // Compute the set of protocols that is implied by either the common type or
7108 // the protocols within the intersection.
7109 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7110 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7111
7112 // Remove any implied protocols from the list of inherited protocols.
7113 if (!ImpliedProtocols.empty()) {
7114 IntersectionSet.erase(
7115 std::remove_if(IntersectionSet.begin(),
7116 IntersectionSet.end(),
7117 [&](ObjCProtocolDecl *proto) -> bool {
7118 return ImpliedProtocols.count(proto) > 0;
7119 }),
7120 IntersectionSet.end());
7121 }
7122
7123 // Sort the remaining protocols by name.
7124 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7125 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007126}
7127
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007128/// Determine whether the first type is a subtype of the second.
7129static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7130 QualType rhs) {
7131 // Common case: two object pointers.
7132 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7133 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7134 if (lhsOPT && rhsOPT)
7135 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7136
7137 // Two block pointers.
7138 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7139 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7140 if (lhsBlock && rhsBlock)
7141 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7142
7143 // If either is an unqualified 'id' and the other is a block, it's
7144 // acceptable.
7145 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7146 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7147 return true;
7148
7149 return false;
7150}
7151
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007152// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007153static bool sameObjCTypeArgs(ASTContext &ctx,
7154 const ObjCInterfaceDecl *iface,
7155 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007156 ArrayRef<QualType> rhsArgs,
7157 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007158 if (lhsArgs.size() != rhsArgs.size())
7159 return false;
7160
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007161 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007162 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007163 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7164 continue;
7165
7166 switch (typeParams->begin()[i]->getVariance()) {
7167 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007168 if (!stripKindOf ||
7169 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7170 rhsArgs[i].stripObjCKindOfType(ctx))) {
7171 return false;
7172 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007173 break;
7174
7175 case ObjCTypeParamVariance::Covariant:
7176 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7177 return false;
7178 break;
7179
7180 case ObjCTypeParamVariance::Contravariant:
7181 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7182 return false;
7183 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007184 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007185 }
7186
7187 return true;
7188}
7189
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007190QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007191 const ObjCObjectPointerType *Lptr,
7192 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007193 const ObjCObjectType *LHS = Lptr->getObjectType();
7194 const ObjCObjectType *RHS = Rptr->getObjectType();
7195 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7196 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007197
7198 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007199 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007200
Manman Renc46f7d12016-05-06 19:35:02 +00007201 // When either LHS or RHS is a kindof type, we should return a kindof type.
7202 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7203 // kindof(A).
7204 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7205
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007206 // Follow the left-hand side up the class hierarchy until we either hit a
7207 // root or find the RHS. Record the ancestors in case we don't find it.
7208 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7209 LHSAncestors;
7210 while (true) {
7211 // Record this ancestor. We'll need this if the common type isn't in the
7212 // path from the LHS to the root.
7213 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007214
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007215 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7216 // Get the type arguments.
7217 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7218 bool anyChanges = false;
7219 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7220 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007221 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7222 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007223 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007224 return QualType();
7225 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7226 // If only one has type arguments, the result will not have type
7227 // arguments.
7228 LHSTypeArgs = { };
7229 anyChanges = true;
7230 }
7231
7232 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007233 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007234 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7235 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007236 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007237 anyChanges = true;
7238
7239 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007240 // If we need to return a kindof type but LHS is not a kindof type, we
7241 // build a new result type.
7242 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007243 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007244 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007245 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007246 return getObjCObjectPointerType(Result);
7247 }
7248
7249 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007250 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007251
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007252 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007253 QualType LHSSuperType = LHS->getSuperClassType();
7254 if (LHSSuperType.isNull())
7255 break;
7256
7257 LHS = LHSSuperType->castAs<ObjCObjectType>();
7258 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007259
7260 // We didn't find anything by following the LHS to its root; now check
7261 // the RHS against the cached set of ancestors.
7262 while (true) {
7263 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7264 if (KnownLHS != LHSAncestors.end()) {
7265 LHS = KnownLHS->second;
7266
7267 // Get the type arguments.
7268 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7269 bool anyChanges = false;
7270 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7271 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007272 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7273 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007274 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007275 return QualType();
7276 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7277 // If only one has type arguments, the result will not have type
7278 // arguments.
7279 RHSTypeArgs = { };
7280 anyChanges = true;
7281 }
7282
7283 // Compute the intersection of protocols.
7284 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7285 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7286 Protocols);
7287 if (!Protocols.empty())
7288 anyChanges = true;
7289
Manman Renc46f7d12016-05-06 19:35:02 +00007290 // If we need to return a kindof type but RHS is not a kindof type, we
7291 // build a new result type.
7292 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007293 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007294 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007295 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007296 return getObjCObjectPointerType(Result);
7297 }
7298
7299 return getObjCObjectPointerType(QualType(RHS, 0));
7300 }
7301
7302 // Find the superclass of the RHS.
7303 QualType RHSSuperType = RHS->getSuperClassType();
7304 if (RHSSuperType.isNull())
7305 break;
7306
7307 RHS = RHSSuperType->castAs<ObjCObjectType>();
7308 }
7309
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007310 return QualType();
7311}
7312
John McCall8b07ec22010-05-15 11:32:37 +00007313bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7314 const ObjCObjectType *RHS) {
7315 assert(LHS->getInterface() && "LHS is not an interface type");
7316 assert(RHS->getInterface() && "RHS is not an interface type");
7317
Chris Lattner49af6a42008-04-07 06:51:04 +00007318 // Verify that the base decls are compatible: the RHS must be a subclass of
7319 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007320 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7321 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7322 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007323 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007324
Douglas Gregore83b9562015-07-07 03:57:53 +00007325 // If the LHS has protocol qualifiers, determine whether all of them are
7326 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7327 // LHS).
7328 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007329 // OK if conversion of LHS to SuperClass results in narrowing of types
7330 // ; i.e., SuperClass may implement at least one of the protocols
7331 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7332 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7333 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7334 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7335 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7336 // qualifiers.
7337 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007338 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007339 // If there is no protocols associated with RHS, it is not a match.
7340 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007341 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007342
7343 for (const auto *LHSProto : LHS->quals()) {
7344 bool SuperImplementsProtocol = false;
7345 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7346 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7347 SuperImplementsProtocol = true;
7348 break;
7349 }
7350 if (!SuperImplementsProtocol)
7351 return false;
7352 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007353 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007354
7355 // If the LHS is specialized, we may need to check type arguments.
7356 if (LHS->isSpecialized()) {
7357 // Follow the superclass chain until we've matched the LHS class in the
7358 // hierarchy. This substitutes type arguments through.
7359 const ObjCObjectType *RHSSuper = RHS;
7360 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7361 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7362
7363 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007364 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007365 !sameObjCTypeArgs(*this, LHS->getInterface(),
7366 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007367 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007368 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007369 }
7370 }
7371
7372 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007373}
7374
Steve Naroffb7605152009-02-12 17:52:19 +00007375bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7376 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007377 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7378 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007379
Steve Naroff7cae42b2009-07-10 23:34:53 +00007380 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007381 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007382
7383 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7384 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007385}
7386
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007387bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7388 return canAssignObjCInterfaces(
7389 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7390 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7391}
7392
Mike Stump11289f42009-09-09 15:08:12 +00007393/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007394/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007395/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007396/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007397bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7398 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007399 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007400 return hasSameType(LHS, RHS);
7401
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007402 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007403}
7404
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007405bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007406 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007407}
7408
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007409bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7410 return !mergeTypes(LHS, RHS, true).isNull();
7411}
7412
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007413/// mergeTransparentUnionType - if T is a transparent union type and a member
7414/// of T is compatible with SubType, return the merged type, else return
7415/// QualType()
7416QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7417 bool OfBlockPointer,
7418 bool Unqualified) {
7419 if (const RecordType *UT = T->getAsUnionType()) {
7420 RecordDecl *UD = UT->getDecl();
7421 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007422 for (const auto *I : UD->fields()) {
7423 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007424 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7425 if (!MT.isNull())
7426 return MT;
7427 }
7428 }
7429 }
7430
7431 return QualType();
7432}
7433
Alp Toker9cacbab2014-01-20 20:26:09 +00007434/// mergeFunctionParameterTypes - merge two types which appear as function
7435/// parameter types
7436QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7437 bool OfBlockPointer,
7438 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007439 // GNU extension: two types are compatible if they appear as a function
7440 // argument, one of the types is a transparent union type and the other
7441 // type is compatible with a union member
7442 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7443 Unqualified);
7444 if (!lmerge.isNull())
7445 return lmerge;
7446
7447 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7448 Unqualified);
7449 if (!rmerge.isNull())
7450 return rmerge;
7451
7452 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7453}
7454
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007455QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007456 bool OfBlockPointer,
7457 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007458 const FunctionType *lbase = lhs->getAs<FunctionType>();
7459 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007460 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7461 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007462 bool allLTypes = true;
7463 bool allRTypes = true;
7464
7465 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007466 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007467 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007468 QualType RHS = rbase->getReturnType();
7469 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007470 bool UnqualifiedResult = Unqualified;
7471 if (!UnqualifiedResult)
7472 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007473 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007474 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007475 else
Alp Toker314cc812014-01-25 16:55:45 +00007476 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007477 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007478 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007479
7480 if (Unqualified)
7481 retType = retType.getUnqualifiedType();
7482
Alp Toker314cc812014-01-25 16:55:45 +00007483 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7484 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007485 if (Unqualified) {
7486 LRetType = LRetType.getUnqualifiedType();
7487 RRetType = RRetType.getUnqualifiedType();
7488 }
7489
7490 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007491 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007492 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007493 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007494
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007495 // FIXME: double check this
7496 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7497 // rbase->getRegParmAttr() != 0 &&
7498 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007499 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7500 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007501
Douglas Gregor8c940862010-01-18 17:14:39 +00007502 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007503 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007504 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007505
John McCall8c6b56f2010-12-15 01:06:38 +00007506 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007507 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7508 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007509 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7510 return QualType();
7511
John McCall31168b02011-06-15 23:02:42 +00007512 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7513 return QualType();
7514
John McCall8c6b56f2010-12-15 01:06:38 +00007515 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7516 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007517
Rafael Espindola8778c282012-11-29 16:09:03 +00007518 if (lbaseInfo.getNoReturn() != NoReturn)
7519 allLTypes = false;
7520 if (rbaseInfo.getNoReturn() != NoReturn)
7521 allRTypes = false;
7522
John McCall31168b02011-06-15 23:02:42 +00007523 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007524
Eli Friedman47f77112008-08-22 00:56:42 +00007525 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007526 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7527 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007528 // Compatible functions must have the same number of parameters
7529 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007530 return QualType();
7531
7532 // Variadic and non-variadic functions aren't compatible
7533 if (lproto->isVariadic() != rproto->isVariadic())
7534 return QualType();
7535
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007536 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7537 return QualType();
7538
John McCall18afab72016-03-01 00:49:02 +00007539 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007540 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007541
7542 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007543 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007544 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7545 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7546 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7547 QualType paramType = mergeFunctionParameterTypes(
7548 lParamType, rParamType, OfBlockPointer, Unqualified);
7549 if (paramType.isNull())
7550 return QualType();
7551
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007552 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007553 paramType = paramType.getUnqualifiedType();
7554
7555 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007556 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007557 lParamType = lParamType.getUnqualifiedType();
7558 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007559 }
Alp Toker601b22c2014-01-21 23:35:24 +00007560
7561 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007562 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007563 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007564 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007565 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007566
Eli Friedman47f77112008-08-22 00:56:42 +00007567 if (allLTypes) return lhs;
7568 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007569
7570 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7571 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007572 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007573 }
7574
7575 if (lproto) allRTypes = false;
7576 if (rproto) allLTypes = false;
7577
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007578 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007579 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007580 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007581 if (proto->isVariadic()) return QualType();
7582 // Check that the types are compatible with the types that
7583 // would result from default argument promotions (C99 6.7.5.3p15).
7584 // The only types actually affected are promotable integer
7585 // types and floats, which would be passed as a different
7586 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007587 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7588 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007589
Eli Friedman448ce402012-08-30 00:44:15 +00007590 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007591 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007592 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7593 paramTy = Enum->getDecl()->getIntegerType();
7594 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007595 return QualType();
7596 }
Alp Toker601b22c2014-01-21 23:35:24 +00007597
7598 if (paramTy->isPromotableIntegerType() ||
7599 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007600 return QualType();
7601 }
7602
7603 if (allLTypes) return lhs;
7604 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007605
7606 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7607 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007608 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007609 }
7610
7611 if (allLTypes) return lhs;
7612 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007613 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007614}
7615
John McCall433c2e62013-03-21 00:10:07 +00007616/// Given that we have an enum type and a non-enum type, try to merge them.
7617static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7618 QualType other, bool isBlockReturnType) {
7619 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7620 // a signed integer type, or an unsigned integer type.
7621 // Compatibility is based on the underlying type, not the promotion
7622 // type.
7623 QualType underlyingType = ET->getDecl()->getIntegerType();
7624 if (underlyingType.isNull()) return QualType();
7625 if (Context.hasSameType(underlyingType, other))
7626 return other;
7627
7628 // In block return types, we're more permissive and accept any
7629 // integral type of the same size.
7630 if (isBlockReturnType && other->isIntegerType() &&
7631 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7632 return other;
7633
7634 return QualType();
7635}
7636
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007637QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007638 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007639 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007640 // C++ [expr]: If an expression initially has the type "reference to T", the
7641 // type is adjusted to "T" prior to any further analysis, the expression
7642 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007643 // expression is an lvalue unless the reference is an rvalue reference and
7644 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007645 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7646 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007647
7648 if (Unqualified) {
7649 LHS = LHS.getUnqualifiedType();
7650 RHS = RHS.getUnqualifiedType();
7651 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007652
Eli Friedman47f77112008-08-22 00:56:42 +00007653 QualType LHSCan = getCanonicalType(LHS),
7654 RHSCan = getCanonicalType(RHS);
7655
7656 // If two types are identical, they are compatible.
7657 if (LHSCan == RHSCan)
7658 return LHS;
7659
John McCall8ccfcb52009-09-24 19:53:00 +00007660 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007661 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7662 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007663 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007664 if (getLangOpts().OpenCL) {
Yaxun Liuab933942016-04-28 17:34:57 +00007665 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
Yaxun Liua1a87ad2016-04-12 19:43:36 +00007666 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
7667 return QualType();
7668 if (LQuals.isAddressSpaceSupersetOf(RQuals))
7669 return LHS;
7670 if (RQuals.isAddressSpaceSupersetOf(LQuals))
7671 return RHS;
7672 }
John McCall8ccfcb52009-09-24 19:53:00 +00007673 // If any of these qualifiers are different, we have a type
7674 // mismatch.
7675 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007676 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7677 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007678 return QualType();
7679
7680 // Exactly one GC qualifier difference is allowed: __strong is
7681 // okay if the other type has no GC qualifier but is an Objective
7682 // C object pointer (i.e. implicitly strong by default). We fix
7683 // this by pretending that the unqualified type was actually
7684 // qualified __strong.
7685 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7686 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7687 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7688
7689 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7690 return QualType();
7691
7692 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7693 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7694 }
7695 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7696 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7697 }
Eli Friedman47f77112008-08-22 00:56:42 +00007698 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007699 }
7700
7701 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007702
Eli Friedmandcca6332009-06-01 01:22:52 +00007703 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7704 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007705
Chris Lattnerfd652912008-01-14 05:45:46 +00007706 // We want to consider the two function types to be the same for these
7707 // comparisons, just force one to the other.
7708 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7709 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007710
7711 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007712 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7713 LHSClass = Type::ConstantArray;
7714 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7715 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007716
John McCall8b07ec22010-05-15 11:32:37 +00007717 // ObjCInterfaces are just specialized ObjCObjects.
7718 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7719 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7720
Nate Begemance4d7fc2008-04-18 23:10:10 +00007721 // Canonicalize ExtVector -> Vector.
7722 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7723 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007724
Chris Lattner95554662008-04-07 05:43:21 +00007725 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007726 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007727 // Note that we only have special rules for turning block enum
7728 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007729 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007730 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007731 }
John McCall9dd450b2009-09-21 23:43:11 +00007732 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007733 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007734 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007735 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007736 if (OfBlockPointer && !BlockReturnType) {
7737 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7738 return LHS;
7739 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7740 return RHS;
7741 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007742
Eli Friedman47f77112008-08-22 00:56:42 +00007743 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007744 }
Eli Friedman47f77112008-08-22 00:56:42 +00007745
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007746 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007747 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007748#define TYPE(Class, Base)
7749#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007750#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007751#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7752#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7753#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007754 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007755
Richard Smith27d807c2013-04-30 13:56:41 +00007756 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007757 case Type::LValueReference:
7758 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007759 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007760 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007761
John McCall8b07ec22010-05-15 11:32:37 +00007762 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007763 case Type::IncompleteArray:
7764 case Type::VariableArray:
7765 case Type::FunctionProto:
7766 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007767 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007768
Chris Lattnerfd652912008-01-14 05:45:46 +00007769 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007770 {
7771 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007772 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7773 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007774 if (Unqualified) {
7775 LHSPointee = LHSPointee.getUnqualifiedType();
7776 RHSPointee = RHSPointee.getUnqualifiedType();
7777 }
7778 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7779 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007780 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007781 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007782 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007783 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007784 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007785 return getPointerType(ResultType);
7786 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007787 case Type::BlockPointer:
7788 {
7789 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007790 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7791 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007792 if (Unqualified) {
7793 LHSPointee = LHSPointee.getUnqualifiedType();
7794 RHSPointee = RHSPointee.getUnqualifiedType();
7795 }
7796 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7797 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007798 if (ResultType.isNull()) return QualType();
7799 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7800 return LHS;
7801 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7802 return RHS;
7803 return getBlockPointerType(ResultType);
7804 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007805 case Type::Atomic:
7806 {
7807 // Merge two pointer types, while trying to preserve typedef info
7808 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7809 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7810 if (Unqualified) {
7811 LHSValue = LHSValue.getUnqualifiedType();
7812 RHSValue = RHSValue.getUnqualifiedType();
7813 }
7814 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7815 Unqualified);
7816 if (ResultType.isNull()) return QualType();
7817 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7818 return LHS;
7819 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7820 return RHS;
7821 return getAtomicType(ResultType);
7822 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007823 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007824 {
7825 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7826 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7827 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7828 return QualType();
7829
7830 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7831 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007832 if (Unqualified) {
7833 LHSElem = LHSElem.getUnqualifiedType();
7834 RHSElem = RHSElem.getUnqualifiedType();
7835 }
7836
7837 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007838 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007839 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7840 return LHS;
7841 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7842 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007843 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7844 ArrayType::ArraySizeModifier(), 0);
7845 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7846 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007847 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7848 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007849 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7850 return LHS;
7851 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7852 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007853 if (LVAT) {
7854 // FIXME: This isn't correct! But tricky to implement because
7855 // the array's size has to be the size of LHS, but the type
7856 // has to be different.
7857 return LHS;
7858 }
7859 if (RVAT) {
7860 // FIXME: This isn't correct! But tricky to implement because
7861 // the array's size has to be the size of RHS, but the type
7862 // has to be different.
7863 return RHS;
7864 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007865 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7866 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007867 return getIncompleteArrayType(ResultType,
7868 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007869 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007870 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007871 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007872 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007873 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007874 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007875 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007876 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007877 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007878 case Type::Complex:
7879 // Distinct complex types are incompatible.
7880 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007881 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007882 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007883 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7884 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007885 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007886 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007887 case Type::ObjCObject: {
7888 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007889 // FIXME: This should be type compatibility, e.g. whether
7890 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007891 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7892 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7893 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007894 return LHS;
7895
Eli Friedman47f77112008-08-22 00:56:42 +00007896 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007897 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007898 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007899 if (OfBlockPointer) {
7900 if (canAssignObjCInterfacesInBlockPointer(
7901 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007902 RHS->getAs<ObjCObjectPointerType>(),
7903 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007904 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007905 return QualType();
7906 }
John McCall9dd450b2009-09-21 23:43:11 +00007907 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7908 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007909 return LHS;
7910
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007911 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007912 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00007913 case Type::Pipe:
7914 {
7915 // Merge two pointer types, while trying to preserve typedef info
7916 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
7917 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
7918 if (Unqualified) {
7919 LHSValue = LHSValue.getUnqualifiedType();
7920 RHSValue = RHSValue.getUnqualifiedType();
7921 }
7922 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7923 Unqualified);
7924 if (ResultType.isNull()) return QualType();
7925 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7926 return LHS;
7927 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7928 return RHS;
7929 return getPipeType(ResultType);
7930 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007931 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007932
David Blaikie8a40f702012-01-17 06:56:22 +00007933 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007934}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007935
John McCall18afab72016-03-01 00:49:02 +00007936bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
7937 const FunctionProtoType *firstFnType,
7938 const FunctionProtoType *secondFnType) {
7939 // Fast path: if the first type doesn't have ext parameter infos,
7940 // we match if and only if they second type also doesn't have them.
7941 if (!firstFnType->hasExtParameterInfos())
7942 return !secondFnType->hasExtParameterInfos();
7943
7944 // Otherwise, we can only match if the second type has them.
7945 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007946 return false;
John McCall18afab72016-03-01 00:49:02 +00007947
7948 auto firstEPI = firstFnType->getExtParameterInfos();
7949 auto secondEPI = secondFnType->getExtParameterInfos();
7950 assert(firstEPI.size() == secondEPI.size());
7951
7952 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
7953 if (firstEPI[i] != secondEPI[i])
7954 return false;
7955 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007956 return true;
7957}
7958
Chandler Carruth21c90602015-12-30 03:24:14 +00007959void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
7960 ObjCLayouts[CD] = nullptr;
7961}
7962
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007963/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7964/// 'RHS' attributes and returns the merged version; including for function
7965/// return types.
7966QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7967 QualType LHSCan = getCanonicalType(LHS),
7968 RHSCan = getCanonicalType(RHS);
7969 // If two types are identical, they are compatible.
7970 if (LHSCan == RHSCan)
7971 return LHS;
7972 if (RHSCan->isFunctionType()) {
7973 if (!LHSCan->isFunctionType())
7974 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007975 QualType OldReturnType =
7976 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007977 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007978 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007979 QualType ResReturnType =
7980 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7981 if (ResReturnType.isNull())
7982 return QualType();
7983 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7984 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7985 // In either case, use OldReturnType to build the new function type.
7986 const FunctionType *F = LHS->getAs<FunctionType>();
7987 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007988 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7989 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007990 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007991 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007992 return ResultType;
7993 }
7994 }
7995 return QualType();
7996 }
7997
7998 // If the qualifiers are different, the types can still be merged.
7999 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8000 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8001 if (LQuals != RQuals) {
8002 // If any of these qualifiers are different, we have a type mismatch.
8003 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8004 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8005 return QualType();
8006
8007 // Exactly one GC qualifier difference is allowed: __strong is
8008 // okay if the other type has no GC qualifier but is an Objective
8009 // C object pointer (i.e. implicitly strong by default). We fix
8010 // this by pretending that the unqualified type was actually
8011 // qualified __strong.
8012 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8013 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8014 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8015
8016 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8017 return QualType();
8018
8019 if (GC_L == Qualifiers::Strong)
8020 return LHS;
8021 if (GC_R == Qualifiers::Strong)
8022 return RHS;
8023 return QualType();
8024 }
8025
8026 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8027 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8028 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8029 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8030 if (ResQT == LHSBaseQT)
8031 return LHS;
8032 if (ResQT == RHSBaseQT)
8033 return RHS;
8034 }
8035 return QualType();
8036}
8037
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008038//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008039// Integer Predicates
8040//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008041
Jay Foad39c79802011-01-12 09:06:06 +00008042unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008043 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008044 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008045 if (T->isBooleanType())
8046 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008047 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008048 return (unsigned)getTypeSize(T);
8049}
8050
Abramo Bagnara13640492012-09-09 10:21:24 +00008051QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008052 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008053
8054 // Turn <4 x signed int> -> <4 x unsigned int>
8055 if (const VectorType *VTy = T->getAs<VectorType>())
8056 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008057 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008058
8059 // For enums, we return the unsigned version of the base type.
8060 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008061 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008062
8063 const BuiltinType *BTy = T->getAs<BuiltinType>();
8064 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008065 switch (BTy->getKind()) {
8066 case BuiltinType::Char_S:
8067 case BuiltinType::SChar:
8068 return UnsignedCharTy;
8069 case BuiltinType::Short:
8070 return UnsignedShortTy;
8071 case BuiltinType::Int:
8072 return UnsignedIntTy;
8073 case BuiltinType::Long:
8074 return UnsignedLongTy;
8075 case BuiltinType::LongLong:
8076 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008077 case BuiltinType::Int128:
8078 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008079 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008080 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008081 }
8082}
8083
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008084ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008085
Richard Smith1fa5d642013-05-11 05:45:24 +00008086void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8087 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008088
8089//===----------------------------------------------------------------------===//
8090// Builtin Type Computation
8091//===----------------------------------------------------------------------===//
8092
8093/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008094/// pointer over the consumed characters. This returns the resultant type. If
8095/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8096/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8097/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008098///
8099/// RequiresICE is filled in on return to indicate whether the value is required
8100/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008101static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008102 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008103 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008104 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008105 // Modifiers.
8106 int HowLong = 0;
8107 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008108 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008109
Chris Lattnerdc226c22010-10-01 22:42:38 +00008110 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008111 bool Done = false;
8112 while (!Done) {
8113 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008114 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008115 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008116 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008117 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008118 case 'S':
8119 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8120 assert(!Signed && "Can't use 'S' modifier multiple times!");
8121 Signed = true;
8122 break;
8123 case 'U':
8124 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008125 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008126 Unsigned = true;
8127 break;
8128 case 'L':
8129 assert(HowLong <= 2 && "Can't have LLLL modifier");
8130 ++HowLong;
8131 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008132 case 'W':
8133 // This modifier represents int64 type.
8134 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8135 switch (Context.getTargetInfo().getInt64Type()) {
8136 default:
8137 llvm_unreachable("Unexpected integer type");
8138 case TargetInfo::SignedLong:
8139 HowLong = 1;
8140 break;
8141 case TargetInfo::SignedLongLong:
8142 HowLong = 2;
8143 break;
8144 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008145 }
8146 }
8147
8148 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008149
Chris Lattnerecd79c62009-06-14 00:45:47 +00008150 // Read the base type.
8151 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008152 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008153 case 'v':
8154 assert(HowLong == 0 && !Signed && !Unsigned &&
8155 "Bad modifiers used with 'v'!");
8156 Type = Context.VoidTy;
8157 break;
Jack Carter24bef982013-08-15 15:16:57 +00008158 case 'h':
8159 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008160 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008161 Type = Context.HalfTy;
8162 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008163 case 'f':
8164 assert(HowLong == 0 && !Signed && !Unsigned &&
8165 "Bad modifiers used with 'f'!");
8166 Type = Context.FloatTy;
8167 break;
8168 case 'd':
8169 assert(HowLong < 2 && !Signed && !Unsigned &&
8170 "Bad modifiers used with 'd'!");
8171 if (HowLong)
8172 Type = Context.LongDoubleTy;
8173 else
8174 Type = Context.DoubleTy;
8175 break;
8176 case 's':
8177 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8178 if (Unsigned)
8179 Type = Context.UnsignedShortTy;
8180 else
8181 Type = Context.ShortTy;
8182 break;
8183 case 'i':
8184 if (HowLong == 3)
8185 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8186 else if (HowLong == 2)
8187 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8188 else if (HowLong == 1)
8189 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8190 else
8191 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8192 break;
8193 case 'c':
8194 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8195 if (Signed)
8196 Type = Context.SignedCharTy;
8197 else if (Unsigned)
8198 Type = Context.UnsignedCharTy;
8199 else
8200 Type = Context.CharTy;
8201 break;
8202 case 'b': // boolean
8203 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8204 Type = Context.BoolTy;
8205 break;
8206 case 'z': // size_t.
8207 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8208 Type = Context.getSizeType();
8209 break;
8210 case 'F':
8211 Type = Context.getCFConstantStringType();
8212 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008213 case 'G':
8214 Type = Context.getObjCIdType();
8215 break;
8216 case 'H':
8217 Type = Context.getObjCSelType();
8218 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008219 case 'M':
8220 Type = Context.getObjCSuperType();
8221 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008222 case 'a':
8223 Type = Context.getBuiltinVaListType();
8224 assert(!Type.isNull() && "builtin va list type not initialized!");
8225 break;
8226 case 'A':
8227 // This is a "reference" to a va_list; however, what exactly
8228 // this means depends on how va_list is defined. There are two
8229 // different kinds of va_list: ones passed by value, and ones
8230 // passed by reference. An example of a by-value va_list is
8231 // x86, where va_list is a char*. An example of by-ref va_list
8232 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8233 // we want this argument to be a char*&; for x86-64, we want
8234 // it to be a __va_list_tag*.
8235 Type = Context.getBuiltinVaListType();
8236 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008237 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008238 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008239 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008240 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008241 break;
8242 case 'V': {
8243 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008244 unsigned NumElements = strtoul(Str, &End, 10);
8245 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008246 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008247
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008248 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8249 RequiresICE, false);
8250 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008251
8252 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008253 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008254 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008255 break;
8256 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008257 case 'E': {
8258 char *End;
8259
8260 unsigned NumElements = strtoul(Str, &End, 10);
8261 assert(End != Str && "Missing vector size");
8262
8263 Str = End;
8264
8265 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8266 false);
8267 Type = Context.getExtVectorType(ElementType, NumElements);
8268 break;
8269 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008270 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008271 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8272 false);
8273 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008274 Type = Context.getComplexType(ElementType);
8275 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008276 }
8277 case 'Y' : {
8278 Type = Context.getPointerDiffType();
8279 break;
8280 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008281 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008282 Type = Context.getFILEType();
8283 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008284 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008285 return QualType();
8286 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008287 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008288 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008289 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008290 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008291 else
8292 Type = Context.getjmp_bufType();
8293
Mike Stump2adb4da2009-07-28 23:47:15 +00008294 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008295 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008296 return QualType();
8297 }
8298 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008299 case 'K':
8300 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8301 Type = Context.getucontext_tType();
8302
8303 if (Type.isNull()) {
8304 Error = ASTContext::GE_Missing_ucontext;
8305 return QualType();
8306 }
8307 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008308 case 'p':
8309 Type = Context.getProcessIDType();
8310 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008311 }
Mike Stump11289f42009-09-09 15:08:12 +00008312
Chris Lattnerdc226c22010-10-01 22:42:38 +00008313 // If there are modifiers and if we're allowed to parse them, go for it.
8314 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008315 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008316 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008317 default: Done = true; --Str; break;
8318 case '*':
8319 case '&': {
8320 // Both pointers and references can have their pointee types
8321 // qualified with an address space.
8322 char *End;
8323 unsigned AddrSpace = strtoul(Str, &End, 10);
8324 if (End != Str && AddrSpace != 0) {
8325 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8326 Str = End;
8327 }
8328 if (c == '*')
8329 Type = Context.getPointerType(Type);
8330 else
8331 Type = Context.getLValueReferenceType(Type);
8332 break;
8333 }
8334 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8335 case 'C':
8336 Type = Type.withConst();
8337 break;
8338 case 'D':
8339 Type = Context.getVolatileType(Type);
8340 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008341 case 'R':
8342 Type = Type.withRestrict();
8343 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008344 }
8345 }
Chris Lattner84733392010-10-01 07:13:18 +00008346
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008347 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008348 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008349
Chris Lattnerecd79c62009-06-14 00:45:47 +00008350 return Type;
8351}
8352
8353/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008354QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008355 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008356 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008357 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008358
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008359 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008360
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008361 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008362 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008363 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8364 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008365 if (Error != GE_None)
8366 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008367
8368 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8369
Chris Lattnerecd79c62009-06-14 00:45:47 +00008370 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008371 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008372 if (Error != GE_None)
8373 return QualType();
8374
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008375 // If this argument is required to be an IntegerConstantExpression and the
8376 // caller cares, fill in the bitmask we return.
8377 if (RequiresICE && IntegerConstantArgs)
8378 *IntegerConstantArgs |= 1 << ArgTypes.size();
8379
Chris Lattnerecd79c62009-06-14 00:45:47 +00008380 // Do array -> pointer decay. The builtin should use the decayed type.
8381 if (Ty->isArrayType())
8382 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008383
Chris Lattnerecd79c62009-06-14 00:45:47 +00008384 ArgTypes.push_back(Ty);
8385 }
8386
David Majnemerba3e5ec2015-03-13 18:26:17 +00008387 if (Id == Builtin::BI__GetExceptionInfo)
8388 return QualType();
8389
Chris Lattnerecd79c62009-06-14 00:45:47 +00008390 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8391 "'.' should only occur at end of builtin type list!");
8392
Reid Kleckner78af0702013-08-27 23:08:25 +00008393 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008394 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8395
8396 bool Variadic = (TypeStr[0] == '.');
8397
8398 // We really shouldn't be making a no-proto type here, especially in C++.
8399 if (ArgTypes.empty() && Variadic)
8400 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008401
John McCalldb40c7f2010-12-14 08:05:40 +00008402 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008403 EPI.ExtInfo = EI;
8404 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00008405
Jordan Rose5c382722013-03-08 21:51:21 +00008406 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008407}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008408
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008409static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8410 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008411 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008412 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008413
Rafael Espindola3ae00052013-05-13 00:12:11 +00008414 GVALinkage External = GVA_StrongExternal;
8415 switch (FD->getTemplateSpecializationKind()) {
8416 case TSK_Undeclared:
8417 case TSK_ExplicitSpecialization:
8418 External = GVA_StrongExternal;
8419 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008420
Rafael Espindola3ae00052013-05-13 00:12:11 +00008421 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008422 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008423
David Majnemerc3d07332014-05-15 06:25:57 +00008424 // C++11 [temp.explicit]p10:
8425 // [ Note: The intent is that an inline function that is the subject of
8426 // an explicit instantiation declaration will still be implicitly
8427 // instantiated when used so that the body can be considered for
8428 // inlining, but that no out-of-line copy of the inline function would be
8429 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008430 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008431 return GVA_AvailableExternally;
8432
Rafael Espindola3ae00052013-05-13 00:12:11 +00008433 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008434 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008435 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008436 }
8437
8438 if (!FD->isInlined())
8439 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008440
David Majnemer3f021502015-10-08 04:53:31 +00008441 if ((!Context.getLangOpts().CPlusPlus &&
8442 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008443 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008444 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008445 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8446
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008447 // GNU or C99 inline semantics. Determine whether this symbol should be
8448 // externally visible.
8449 if (FD->isInlineDefinitionExternallyVisible())
8450 return External;
8451
8452 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008453 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008454 }
8455
David Majnemer54e3ba52014-04-02 23:17:29 +00008456 // Functions specified with extern and inline in -fms-compatibility mode
8457 // forcibly get emitted. While the body of the function cannot be later
8458 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008459 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008460 return GVA_StrongODR;
8461
David Majnemer27d69db2014-04-28 22:17:59 +00008462 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008463}
8464
Artem Belevichca2b9512016-05-02 20:30:03 +00008465static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8466 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008467 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8468 // dllexport/dllimport on inline functions.
8469 if (D->hasAttr<DLLImportAttr>()) {
8470 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8471 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008472 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008473 if (L == GVA_DiscardableODR)
8474 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008475 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8476 D->hasAttr<CUDAGlobalAttr>()) {
8477 // Device-side functions with __global__ attribute must always be
8478 // visible externally so they can be launched from host.
8479 if (L == GVA_DiscardableODR || L == GVA_Internal)
8480 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008481 }
8482 return L;
8483}
8484
8485GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
Artem Belevichca2b9512016-05-02 20:30:03 +00008486 return adjustGVALinkageForAttributes(
8487 *this, basicGVALinkageForFunction(*this, FD), FD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008488}
8489
8490static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8491 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008492 if (!VD->isExternallyVisible())
8493 return GVA_Internal;
8494
David Majnemer27d69db2014-04-28 22:17:59 +00008495 if (VD->isStaticLocal()) {
8496 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8497 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8498 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8499 LexicalContext = LexicalContext->getLexicalParent();
8500
Richard Smith9e2341d2015-03-23 03:25:59 +00008501 // Let the static local variable inherit its linkage from the nearest
David Majnemer27d69db2014-04-28 22:17:59 +00008502 // enclosing function.
8503 if (LexicalContext)
8504 StaticLocalLinkage =
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008505 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
David Majnemer27d69db2014-04-28 22:17:59 +00008506
8507 // GVA_StrongODR function linkage is stronger than what we need,
8508 // downgrade to GVA_DiscardableODR.
8509 // This allows us to discard the variable if we never end up needing it.
8510 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8511 : StaticLocalLinkage;
8512 }
8513
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008514 // MSVC treats in-class initialized static data members as definitions.
8515 // By giving them non-strong linkage, out-of-line definitions won't
8516 // cause link errors.
8517 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8518 return GVA_DiscardableODR;
8519
Richard Smithd9b90092016-07-02 01:32:16 +00008520 // Most non-template variables have strong linkage; inline variables are
8521 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8522 GVALinkage StrongLinkage;
8523 switch (Context.getInlineVariableDefinitionKind(VD)) {
8524 case ASTContext::InlineVariableDefinitionKind::None:
8525 StrongLinkage = GVA_StrongExternal;
8526 break;
8527 case ASTContext::InlineVariableDefinitionKind::Weak:
8528 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008529 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008530 break;
8531 case ASTContext::InlineVariableDefinitionKind::Strong:
8532 StrongLinkage = GVA_StrongODR;
8533 break;
8534 }
Richard Smith62f19e72016-06-25 00:15:56 +00008535
Richard Smith8809a0c2013-09-27 20:14:12 +00008536 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008537 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008538 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008539
David Majnemer6d1780c2015-07-17 23:36:49 +00008540 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008541 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8542 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008543 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008544 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008545
Rafael Espindola3ae00052013-05-13 00:12:11 +00008546 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008547 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008548
David Majnemer27d69db2014-04-28 22:17:59 +00008549 case TSK_ExplicitInstantiationDeclaration:
8550 return GVA_AvailableExternally;
8551
Rafael Espindola3ae00052013-05-13 00:12:11 +00008552 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008553 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008554 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008555
8556 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008557}
8558
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008559GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008560 return adjustGVALinkageForAttributes(
8561 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008562}
8563
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00008564bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008565 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8566 if (!VD->isFileVarDecl())
8567 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008568 // Global named register variables (GNU extension) are never emitted.
8569 if (VD->getStorageClass() == SC_Register)
8570 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008571 if (VD->getDescribedVarTemplate() ||
8572 isa<VarTemplatePartialSpecializationDecl>(VD))
8573 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008574 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8575 // We never need to emit an uninstantiated function template.
8576 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8577 return false;
Nico Weber66220292016-03-02 17:28:48 +00008578 } else if (isa<PragmaCommentDecl>(D))
8579 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00008580 else if (isa<OMPThreadPrivateDecl>(D) ||
8581 D->hasAttr<OMPDeclareTargetDeclAttr>())
8582 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00008583 else if (isa<PragmaDetectMismatchDecl>(D))
8584 return true;
Nico Weber66220292016-03-02 17:28:48 +00008585 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00008586 return !D->getDeclContext()->isDependentContext();
8587 else if (isa<OMPDeclareReductionDecl>(D))
8588 return !D->getDeclContext()->isDependentContext();
Alexey Bataev97720002014-11-11 04:05:39 +00008589 else
Richard Smith5205a8c2013-04-01 20:22:16 +00008590 return false;
8591
8592 // If this is a member of a class template, we do not need to emit it.
8593 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008594 return false;
8595
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008596 // Weak references don't produce any output by themselves.
8597 if (D->hasAttr<WeakRefAttr>())
8598 return false;
8599
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008600 // Aliases and used decls are required.
8601 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8602 return true;
8603
8604 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8605 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008606 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00008607 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008608
8609 // Constructors and destructors are required.
8610 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8611 return true;
8612
John McCall6bd2a892013-01-25 22:31:03 +00008613 // The key function for a class is required. This rule only comes
8614 // into play when inline functions can be key functions, though.
8615 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8616 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8617 const CXXRecordDecl *RD = MD->getParent();
8618 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8619 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8620 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8621 return true;
8622 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008623 }
8624 }
8625
8626 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8627
8628 // static, static inline, always_inline, and extern inline functions can
8629 // always be deferred. Normal inline functions can be deferred in C99/C++.
8630 // Implicit template instantiations can also be deferred in C++.
David Majnemer27d69db2014-04-28 22:17:59 +00008631 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8632 Linkage == GVA_DiscardableODR)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008633 return false;
8634 return true;
8635 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008636
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008637 const VarDecl *VD = cast<VarDecl>(D);
8638 assert(VD->isFileVarDecl() && "Expected file scoped var");
8639
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008640 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8641 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008642 return false;
8643
Richard Smitha0e5e542012-11-12 21:38:00 +00008644 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008645 GVALinkage L = GetGVALinkageForVariable(VD);
David Majnemerc3d07332014-05-15 06:25:57 +00008646 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8647 L != GVA_DiscardableODR)
Richard Smitha0e5e542012-11-12 21:38:00 +00008648 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008649
Richard Smitha0e5e542012-11-12 21:38:00 +00008650 // Variables that have destruction with side-effects are required.
8651 if (VD->getType().isDestructedType())
8652 return true;
8653
8654 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00008655 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8656 !VD->evaluateValue())
Richard Smitha0e5e542012-11-12 21:38:00 +00008657 return true;
8658
8659 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008660}
Charles Davis53c59df2010-08-16 03:33:14 +00008661
Reid Kleckner78af0702013-08-27 23:08:25 +00008662CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8663 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008664 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008665 if (IsCXXMethod)
8666 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008667
Alexey Bataeva7547182016-05-18 09:06:38 +00008668 switch (LangOpts.getDefaultCallingConv()) {
8669 case LangOptions::DCC_None:
8670 break;
8671 case LangOptions::DCC_CDecl:
8672 return CC_C;
8673 case LangOptions::DCC_FastCall:
8674 if (getTargetInfo().hasFeature("sse2"))
8675 return CC_X86FastCall;
8676 break;
8677 case LangOptions::DCC_StdCall:
8678 if (!IsVariadic)
8679 return CC_X86StdCall;
8680 break;
8681 case LangOptions::DCC_VectorCall:
8682 // __vectorcall cannot be applied to variadic functions.
8683 if (!IsVariadic)
8684 return CC_X86VectorCall;
8685 break;
8686 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00008687 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00008688}
8689
Jay Foad39c79802011-01-12 09:06:06 +00008690bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008691 // Pass through to the C++ ABI object
8692 return ABI->isNearlyEmpty(RD);
8693}
8694
Reid Kleckner96f8f932014-02-05 17:27:08 +00008695VTableContextBase *ASTContext::getVTableContext() {
8696 if (!VTContext.get()) {
8697 if (Target->getCXXABI().isMicrosoft())
8698 VTContext.reset(new MicrosoftVTableContext(*this));
8699 else
8700 VTContext.reset(new ItaniumVTableContext(*this));
8701 }
8702 return VTContext.get();
8703}
8704
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008705MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008706 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008707 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008708 case TargetCXXABI::GenericItanium:
8709 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00008710 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00008711 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00008712 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00008713 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00008714 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008715 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008716 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008717 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008718 }
David Blaikie83d382b2011-09-23 05:06:16 +00008719 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008720}
8721
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008722CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008723
8724size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008725 return ASTRecordLayouts.getMemorySize() +
8726 llvm::capacity_in_bytes(ObjCLayouts) +
8727 llvm::capacity_in_bytes(KeyFunctions) +
8728 llvm::capacity_in_bytes(ObjCImpls) +
8729 llvm::capacity_in_bytes(BlockVarCopyInits) +
8730 llvm::capacity_in_bytes(DeclAttrs) +
8731 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8732 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8733 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8734 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8735 llvm::capacity_in_bytes(OverriddenMethods) +
8736 llvm::capacity_in_bytes(Types) +
8737 llvm::capacity_in_bytes(VariableArrayTypes) +
8738 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008739}
Ted Kremenek540017e2011-10-06 05:00:56 +00008740
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008741/// getIntTypeForBitwidth -
8742/// sets integer QualTy according to specified details:
8743/// bitwidth, signed/unsigned.
8744/// Returns empty type if there is no appropriate target types.
8745QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8746 unsigned Signed) const {
8747 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8748 CanQualType QualTy = getFromTargetType(Ty);
8749 if (!QualTy && DestWidth == 128)
8750 return Signed ? Int128Ty : UnsignedInt128Ty;
8751 return QualTy;
8752}
8753
8754/// getRealTypeForBitwidth -
8755/// sets floating point QualTy according to specified bitwidth.
8756/// Returns empty type if there is no appropriate target types.
8757QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8758 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8759 switch (Ty) {
8760 case TargetInfo::Float:
8761 return FloatTy;
8762 case TargetInfo::Double:
8763 return DoubleTy;
8764 case TargetInfo::LongDouble:
8765 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00008766 case TargetInfo::Float128:
8767 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008768 case TargetInfo::NoFloat:
8769 return QualType();
8770 }
8771
8772 llvm_unreachable("Unhandled TargetInfo::RealType value");
8773}
8774
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008775void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8776 if (Number > 1)
8777 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008778}
8779
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008780unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008781 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008782 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008783}
8784
David Majnemer2206bf52014-03-05 08:57:59 +00008785void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8786 if (Number > 1)
8787 StaticLocalNumbers[VD] = Number;
8788}
8789
8790unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00008791 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00008792 return I != StaticLocalNumbers.end() ? I->second : 1;
8793}
8794
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008795MangleNumberingContext &
8796ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008797 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8798 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8799 if (!MCtx)
8800 MCtx = createMangleNumberingContext();
8801 return *MCtx;
8802}
8803
8804MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8805 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008806}
8807
David Majnemere7a818f2015-03-06 18:53:55 +00008808const CXXConstructorDecl *
8809ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8810 return ABI->getCopyConstructorForExceptionObject(
8811 cast<CXXRecordDecl>(RD->getFirstDecl()));
8812}
8813
8814void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8815 CXXConstructorDecl *CD) {
8816 return ABI->addCopyConstructorForExceptionObject(
8817 cast<CXXRecordDecl>(RD->getFirstDecl()),
8818 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8819}
8820
David Majnemerdfa6d202015-03-11 18:36:39 +00008821void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8822 unsigned ParmIdx, Expr *DAE) {
8823 ABI->addDefaultArgExprForConstructor(
8824 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8825}
8826
8827Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8828 unsigned ParmIdx) {
8829 return ABI->getDefaultArgExprForConstructor(
8830 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8831}
8832
David Majnemer00350522015-08-31 18:48:39 +00008833void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8834 TypedefNameDecl *DD) {
8835 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8836}
8837
8838TypedefNameDecl *
8839ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8840 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8841}
8842
8843void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8844 DeclaratorDecl *DD) {
8845 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8846}
8847
8848DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8849 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8850}
8851
Ted Kremenek540017e2011-10-06 05:00:56 +00008852void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8853 ParamIndices[D] = index;
8854}
8855
8856unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8857 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8858 assert(I != ParamIndices.end() &&
8859 "ParmIndices lacks entry set by ParmVarDecl");
8860 return I->second;
8861}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008862
Richard Smithe6c01442013-06-05 00:46:14 +00008863APValue *
8864ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8865 bool MayCreate) {
8866 assert(E && E->getStorageDuration() == SD_Static &&
8867 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00008868 if (MayCreate) {
8869 APValue *&MTVI = MaterializedTemporaryValues[E];
8870 if (!MTVI)
8871 MTVI = new (*this) APValue;
8872 return MTVI;
8873 }
Richard Smithe6c01442013-06-05 00:46:14 +00008874
David Majnemer2dcef9e2015-08-13 23:50:15 +00008875 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00008876}
8877
Fariborz Jahanian615de762013-05-28 17:37:39 +00008878bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8879 const llvm::Triple &T = getTargetInfo().getTriple();
8880 if (!T.isOSDarwin())
8881 return false;
8882
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008883 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8884 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8885 return false;
8886
Fariborz Jahanian615de762013-05-28 17:37:39 +00008887 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8888 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8889 uint64_t Size = sizeChars.getQuantity();
8890 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8891 unsigned Align = alignChars.getQuantity();
8892 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8893 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8894}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008895
8896namespace {
8897
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008898ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8899 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008900 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008901 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008902 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008903 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00008904 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008905}
8906
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008907/// Template specializations to abstract away from pointers and TypeLocs.
8908/// @{
8909template <typename T>
8910ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8911 return ast_type_traits::DynTypedNode::create(*Node);
8912}
8913template <>
8914ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8915 return ast_type_traits::DynTypedNode::create(Node);
8916}
8917template <>
8918ast_type_traits::DynTypedNode
8919createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8920 return ast_type_traits::DynTypedNode::create(Node);
8921}
8922/// @}
8923
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008924 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8925 /// parents as defined by the \c RecursiveASTVisitor.
8926 ///
8927 /// Note that the relationship described here is purely in terms of AST
8928 /// traversal - there are other relationships (for example declaration context)
8929 /// in the AST that are better modeled by special matchers.
8930 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008931 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008932 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008933 public:
8934 /// \brief Builds and returns the translation unit's parent map.
8935 ///
8936 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008937 static std::pair<ASTContext::ParentMapPointers *,
8938 ASTContext::ParentMapOtherNodes *>
8939 buildMap(TranslationUnitDecl &TU) {
8940 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8941 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008942 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008943 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008944 }
8945
8946 private:
8947 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8948
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008949 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8950 ASTContext::ParentMapOtherNodes *OtherParents)
8951 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008952
8953 bool shouldVisitTemplateInstantiations() const {
8954 return true;
8955 }
8956 bool shouldVisitImplicitCode() const {
8957 return true;
8958 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008959
Richard Smith85838722015-11-24 03:09:01 +00008960 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8961 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008962 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00008963 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00008964 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008965 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00008966 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00008967 // FIXME: Currently we add the same parent multiple times, but only
8968 // when no memoization data is available for the type.
8969 // For example when we visit all subexpressions of template
8970 // instantiations; this is suboptimal, but benign: the only way to
8971 // visit those is with hasAncestor / hasParent, and those do not create
8972 // new matches.
8973 // The plan is to enable DynTypedNode to be storable in a map or hash
8974 // map. The main problem there is to implement hash functions /
8975 // comparison operators for all types that DynTypedNode supports that
8976 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00008977 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00008978 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008979 if (const auto *D = ParentStack.back().get<Decl>())
8980 NodeOrVector = D;
8981 else if (const auto *S = ParentStack.back().get<Stmt>())
8982 NodeOrVector = S;
8983 else
8984 NodeOrVector =
8985 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00008986 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008987 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8988 auto *Vector = new ASTContext::ParentVector(
8989 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00008990 if (auto *Node =
8991 NodeOrVector
8992 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8993 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00008994 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008995 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00008996
8997 auto *Vector =
8998 NodeOrVector.template get<ASTContext::ParentVector *>();
8999 // Skip duplicates for types that have memoization data.
9000 // We must check that the type has memoization data before calling
9001 // std::find() because DynTypedNode::operator== can't compare all
9002 // types.
9003 bool Found = ParentStack.back().getMemoizationData() &&
9004 std::find(Vector->begin(), Vector->end(),
9005 ParentStack.back()) != Vector->end();
9006 if (!Found)
9007 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009008 }
9009 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009010 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009011 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009012 ParentStack.pop_back();
9013 return Result;
9014 }
9015
9016 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009017 return TraverseNode(DeclNode, DeclNode,
9018 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009019 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009020 }
9021
9022 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009023 return TraverseNode(StmtNode, StmtNode,
9024 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009025 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009026 }
9027
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009028 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009029 return TraverseNode(
9030 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9031 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9032 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009033 }
9034
9035 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9036 return TraverseNode(
9037 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009038 [&] {
9039 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9040 },
9041 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009042 }
9043
9044 ASTContext::ParentMapPointers *Parents;
9045 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009046 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9047
9048 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9049 };
9050
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009051} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009052
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009053template <typename NodeTy, typename MapTy>
9054static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9055 const MapTy &Map) {
9056 auto I = Map.find(Node);
9057 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009058 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009059 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009060 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009061 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009062 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009063 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009064}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009065
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009066ASTContext::DynTypedNodeList
9067ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9068 if (!PointerParents) {
9069 // We always need to run over the whole translation unit, as
9070 // hasAncestor can escape any subtree.
9071 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9072 PointerParents.reset(Maps.first);
9073 OtherParents.reset(Maps.second);
9074 }
9075 if (Node.getNodeKind().hasPointerIdentity())
9076 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9077 return getDynNodeFromMap(Node, *OtherParents);
9078}
9079
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009080bool
9081ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9082 const ObjCMethodDecl *MethodImpl) {
9083 // No point trying to match an unavailable/deprecated mothod.
9084 if (MethodDecl->hasAttr<UnavailableAttr>()
9085 || MethodDecl->hasAttr<DeprecatedAttr>())
9086 return false;
9087 if (MethodDecl->getObjCDeclQualifier() !=
9088 MethodImpl->getObjCDeclQualifier())
9089 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009090 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009091 return false;
9092
9093 if (MethodDecl->param_size() != MethodImpl->param_size())
9094 return false;
9095
9096 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9097 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9098 EF = MethodDecl->param_end();
9099 IM != EM && IF != EF; ++IM, ++IF) {
9100 const ParmVarDecl *DeclVar = (*IF);
9101 const ParmVarDecl *ImplVar = (*IM);
9102 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9103 return false;
9104 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9105 return false;
9106 }
9107 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9108
9109}
Richard Smith053f6c62014-05-16 23:01:30 +00009110
9111// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9112// doesn't include ASTContext.h
9113template
9114clang::LazyGenerationalUpdatePtr<
9115 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9116clang::LazyGenerationalUpdatePtr<
9117 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9118 const clang::ASTContext &Ctx, Decl *Value);